当前位置: 技术问答>java相关
急问题:想把一个文件(例如文本)里的内容导出成为一个String,有什么方法吗?谢谢!
来源: 互联网 发布时间:2015-02-21
本文导语: 想把一个文件(例如文本)里的内容导出成为一个String,有什么方法吗?谢谢! | 试试下面程序 import java.io.*; public class ReadFile { public static void main (String[] args) { //...
想把一个文件(例如文本)里的内容导出成为一个String,有什么方法吗?谢谢!
|
试试下面程序
import java.io.*;
public class ReadFile {
public static void main (String[] args) {
// Create file
if (args.length!=1){
System.out.println("Usage: java ReadFile filename");
return ;
}
File file = new File(args[0]);
StringBuffer sb = new StringBuffer ();
try {
// Create a buffered reader to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
// Read each char and chain.
int i;
while ( (i=in.read())!= -1 ) {
sb.append((char)i);
}
// Close the buffered reader, which also closes the file reader.
in.close();
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
} catch (IOException e2) {
// Catch any other IO exceptions.
e2.printStackTrace();
}
System.out.println(" content of '"+args[0]+"'");
System.out.println(sb.toString());
}
}
import java.io.*;
public class ReadFile {
public static void main (String[] args) {
// Create file
if (args.length!=1){
System.out.println("Usage: java ReadFile filename");
return ;
}
File file = new File(args[0]);
StringBuffer sb = new StringBuffer ();
try {
// Create a buffered reader to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
// Read each char and chain.
int i;
while ( (i=in.read())!= -1 ) {
sb.append((char)i);
}
// Close the buffered reader, which also closes the file reader.
in.close();
} catch (FileNotFoundException e1) {
// If this file does not exist
System.err.println("File not found: " + file);
} catch (IOException e2) {
// Catch any other IO exceptions.
e2.printStackTrace();
}
System.out.println(" content of '"+args[0]+"'");
System.out.println(sb.toString());
}
}
|
修改闹闹一些东西大概会比较好
try {
// Create a buffered reader to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
// Read each char and chain.
String temp;
while ( (temp=in.readLine())!= null ) {
sb.append(temp);
}
// Close the buffered reader, which also closes the file reader.
in.close();
try {
// Create a buffered reader to read each line from a file.
BufferedReader in = new BufferedReader(new FileReader(file));
// Read each char and chain.
String temp;
while ( (temp=in.readLine())!= null ) {
sb.append(temp);
}
// Close the buffered reader, which also closes the file reader.
in.close();
|
先读到一个byte数组里面,然后用String的构造器构造,第一个参数为此数组,第二个参数为字符编码
QQ1818477欢迎交流
QQ1818477欢迎交流
|
看看 FileInputStream RandomAccessFile 类