如何用java读取txt文件

如题所述

你生成了txt文档,必须要将后缀改为.java,然后使用命令行格式的javac命令进行编译,编译后就会出现.class文件,再用命令行格式的java命令进行运行!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-11-11
1.7之前使用 BufferedReader一次一行
1.7 使用 java.nio.file.Files的readAllLines方法一次读到一个List<String>追问

谢谢

追答

1.6:
BufferedReader reader = new BufferedReader(new FileReader(...));
for(String line = reader.readLine(); line != null; line = reader.readLine()){
process(line);

}

第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();

}

}
第3个回答  2012-11-11
java中读取文件用io。

读txt写个最简单的方法

BufferedReader in = new BufferedReader(new FileReader("foo.in"));
String str = "";
String s = in.readLine();
while ( s != null ){
str = str + s;
s = in.readLine();

}
然后文件就读到str中了。还可以使用最标准的io读法,这个就请好好找一本书看看吧。
第4个回答  2012-11-11
..io流啊
FileInputStream in = new FileInputStream(new File("D:\\a\\v.txt"));
byte b[] = new byte[10*1024];
int a = in.read(b);
while(a!=-1){
System.out.println(b);
}本回答被提问者和网友采纳
相似回答