第2个回答 推荐于2017-09-01
用java读取txt文件:
public String read(String path) throws Exception { //读
File f = new File(path);
FileInputStream input = new FileInputStream(f);
BufferedInputStream buf=new BufferedInputStream(input);
byte[] b=new byte[(int) f.length()];
input.read(b);
input.close();
return new String(b);
}
public static void writeFileByByte(String path,String strs,boolean a) throws Exception{ //写
File f1=new File(path);
FileOutputStream out=new FileOutputStream(f1,a);
byte[] b=strs.getBytes();
out.write(b);
out.close();
}
也可以参考JAVA IO。
public class ReadTxtFile {
public static void main(String[] args) throws Exception {
File file = new File("C:\\Users\\795829\\Desktop\\1.txt");
// 字符流读取文件数据
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
System.exit(-1); // TODO 测试用
// 字节流读取文件数据
FileInputStream fis = new FileInputStream(file);
int n = 1024;
byte buffer[] = new byte[n];
while ((fis.read(buffer, 0, n) != -1) && (n > 0)) {
System.out.print(new String(buffer));
}
fis.close();
}
}