java写入文本文件的方法很多,比如FileWriter
FileWriter fw = new FileWriter("D:/Test.txt")String s = "hello world\n"
fw.write(s,0,s.length())
s = "hello world2\n"
fw.write(s,0,s.length())
fw.flush()
这样就写了两行了。其中斜线n是换行符
//读取String pathName = "D:\\1.txt"
BufferedReader br = new BufferedReader(new FileInputStream(pathName))
String line = ""
while((line = br.readLine()) != null){
System.out.println(line)
}
br.close()
//写入
BufferedWriter br = new BufferedWriter(new FileWriter(pathName))
br.write("要写入的内容")
br.flush() //刷新缓冲区的数据到文件
br.close()
试试这个: import java.io.BufferedReader import java.io.File import java.io.FileReader import java.io.IOException public class FileOpenTest { private int count = 0 private FileOpenTest(String filePath) { File f = new File(filePath) try { BufferedReader br = new BufferedReader(new FileReader(f)) while (br.ready()) { br.readLine() count ++ } } catch (IOException e) { e.printStackTrace() } } private int getCount() { return count } public static void main(String[] args) { String filePath = "D:\\test.txt"//文件本地路径 FileOpenTest fot = new FileOpenTest(filePath) System.out.println(fot.getCount()) } }欢迎分享,转载请注明来源:内存溢出
评论列表(0条)