In: Computer Science
Write a program that reads a file (provided as attachment to this assignment) and write the file to a different file with line numbers inserted at the beginning of each line. Such as Example File Input: This is a test Example File Output 1. This is a test. (Please comment and document your code and take your time no rush).
package file;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
public class FileTextTransfer {
public static void main(String[] args) throws
IOException {
File file = new File("."); // .
indicates current directory or project.
String source =
file.getCanonicalPath() + File.separator + "Source.txt";
String dest =
file.getCanonicalPath() + File.separator + "Destination.txt";
// creating a file object
File srcFile = new
File(source);
// providing actual path of
file.
FileInputStream fistream = new
FileInputStream(srcFile);
//BufferedReader class is used to
read the text from a character-based input stream.
BufferedReader bReader = new
BufferedReader(new InputStreamReader(fistream));
// FileWriter class is used to
write character-oriented data to a file along with a boolean
//indicating whether or not to
append the data written. If boolean is true, then data will
be
// written to the end of the file
rather than the beginning.
FileWriter fwriter = new
FileWriter(dest, true);
//BufferedWriter class is used to
provide buffering for File Writer instances.
BufferedWriter outWriter = new
BufferedWriter(fwriter);
String appendLine = null;
int readCount=1,writeCount=1;
// while will execute until
readLine() is not null.
while ((appendLine =
bReader.readLine()) != null) {
readCount++; // reading count increment if reads 1
line.
//Process each
line and add to output to Destination.txt file with line
numbers.
appendLine=writeCount+". "+appendLine;
// writing line
into BufferedWriter.
outWriter.write(appendLine);
// after reading
line providing new line.
outWriter.newLine();
// incrementing
writeCount after writing 1 line .
writeCount++;
}
// if reading successfull and
writing successfull then only print file transfer
successfully.
if(readCount==writeCount)
System.out.println("File text transfer successfully....!!!");
else System.out.println("File not
send successfully.....!!");
// closing the buffer reader
bReader.close();
// closing the buffer writer
outWriter.close();
}
}