java读写文本文件

java读写文本文件,第1张

//读取

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.*

import java.util.Scanner

public class Write_display {

public static void main(String[] args)throws IOException{

BufferedWriter w = new BufferedWriter(new FileWriter("D:\\tester1.txt"))

BufferedReader r = new BufferedReader(new FileReader("D:\\tester1.txt"巧物))

Scanner in = new Scanner(System.in)

String s = in.nextLine()

int c

//向D盘的文件text.txt写旅宽拆入数据

w.write(s)

w.flush()

w.close()

//从text.txt中读取数据并输出

while((c = r.read()) != -1)

System.out.print((char) c)

r.close()

}

}

如果D盘中已经拆枣存在了tester1.txt这个文件并且里面已经有了文本,则可以不用再创建该文件和向该文件写入数据

试慎键试这个: 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()) } }


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/tougao/12260039.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-24
下一篇 2023-05-24

发表评论

登录后才能评论

评论列表(0条)

保存