java读/写文件
Posted hemeiwolong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java读/写文件相关的知识,希望对你有一定的参考价值。
读取文件参考:https://blog.csdn.net/weixin_42129373/article/details/82154471
写入文件参考:https://blog.csdn.net/BanketBoy/article/details/86504704
https://www.cnblogs.com/chenpi/p/5498731.html
1 package text; 2 3 import java.io.BufferedReader; 4 import java.io.BufferedWriter; 5 import java.io.File; 6 import java.io.FileNotFoundException; 7 import java.io.FileReader; 8 import java.io.FileWriter; 9 import java.io.IOException; 10 import java.util.Arrays; 11 import java.util.Scanner; 12 13 import javax.annotation.processing.FilerException; 14 /*从input1.txt和input.txt文本文档轮流按行读取数据并按行写入output.txt文本文档 15 */ 16 17 public class Main { 18 public static void main(String[] args) { 19 String aString = "E:\\\\ACM\\\\test\\\\input1.txt";//文件的路径 20 String bString = "E:\\\\ACM\\\\test\\\\input.txt"; 21 String cString = "E:\\\\ACM\\\\test\\\\output.txt"; 22 23 try { 24 FileReader aFileReader = new FileReader(aString);//字符流用于读/写文件 25 FileReader bFileReader = new FileReader(bString); 26 FileWriter cFileWriter = new FileWriter(cString);//如果写入第二参数为true,则为追加写入 27 28 BufferedReader aBufferedReader = new BufferedReader(aFileReader);//包装字符流以提高效率 29 BufferedReader bBufferedReader = new BufferedReader(bFileReader); 30 BufferedWriter cBufferedWriter = new BufferedWriter(cFileWriter); 31 32 String tempString = aBufferedReader.readLine();//按行读取 33 while (tempString != null) { 34 cBufferedWriter.write(tempString); 35 cBufferedWriter.newLine();//写入换行 36 37 tempString = bBufferedReader.readLine(); 38 cBufferedWriter.write(tempString); 39 cBufferedWriter.newLine(); 40 41 tempString = aBufferedReader.readLine(); 42 } 43 44 cBufferedWriter.close();//关闭流 45 aBufferedReader.close(); 46 bBufferedReader.close(); 47 aFileReader.close(); 48 bFileReader.close(); 49 cFileWriter.close(); 50 } catch (FileNotFoundException e) {//没有try-catch会报错 51 e.printStackTrace(); 52 } catch (IOException e) { 53 e.printStackTrace(); 54 } 55 } 56 }
以上是关于java读/写文件的主要内容,如果未能解决你的问题,请参考以下文章