java读写txt文件
Posted ..小树苗
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java读写txt文件相关的知识,希望对你有一定的参考价值。
写入:
追加内容:
public static void main(String[] args) throws Exception { String data = " This content will append to the end of the file\n"; File file = new File("javaio-appendfile.txt"); if (!file.exists()) { file.createNewFile(); } FileWriter fileWritter = new FileWriter(file.getName(), true); BufferedWriter bufferWritter = new BufferedWriter(fileWritter); bufferWritter.write(data); bufferWritter.close(); System.out.println("Done"); }
不追加的话 写成:
FileWriter fileWritter = new FileWriter(file.getName());
读取:
public static void ss() throws Exception{ String filePath = "C:\\Users\\acer\\Desktop\\111.txt"; StringBuilder sb = new StringBuilder(); String re = ""; String encoding="gbk"; File file=new File(filePath); if(file.isFile() && file.exists()){ //判断文件是否存在 InputStreamReader read = new InputStreamReader( new FileInputStream(file),encoding);//考虑到编码格式 BufferedReader bufferedReader = new BufferedReader(read); String lineTxt = null; int i = 0; while((lineTxt = bufferedReader.readLine()) != null){ lineTxt = lineTxt.trim(); sb.append(lineTxt); i++; } re = sb.toString(); System.out.println(re.length()); read.close(); } }
以上是关于java读写txt文件的主要内容,如果未能解决你的问题,请参考以下文章