src/com/temp/ShowLineNumBeforEachLine.java
xxxxxxxxxx
package com.temp;
import java.io.*;
/**
* @Author lanxiaofang
* @date 2020/11/16 9:18
*/
public class ShowLineNumBeforEachLine {
private final static String url_1 = "D://word1.txt";
private final static String url_2 = "D://word2.txt";
//use BufferedReader and BufferedWriter
public static void main(String[] args) {
useBufferedWriter(url_1, url_2);
}
/**
* useBufferedWriter
*
* @param from_url,to_url Copy the contents from the file in path from_url to the file in path to_url
* Read a line, add line num before the line and write the line, and then create a new line
*/
public static int useBufferedWriter(String from_url, String to_url) {
String thisLine;
int count = 0;
try {
FileReader fileReader = new FileReader(from_url);
FileWriter fileWriter = new FileWriter(to_url);
BufferedReader bufferedReader = new BufferedReader(fileReader);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
while ((thisLine = bufferedReader.readLine()) != null) {
count++;
System.out.println(thisLine);
System.out.println(count+" "+thisLine);
bufferedWriter.write(count+" "+thisLine);
bufferedWriter.newLine();
}
bufferedWriter.flush();
System.out.println("--useBufferedWriter-- had read " + count + " lines. \n--useBufferedWriter-- had writer "+count+" lines.");
} catch (IOException e) {
e.printStackTrace();
return 0;
}
return 1;
}
}