JAVA Program Write a program that will open a text file and extract each line wi
ID: 3686579 • Letter: J
Question
JAVA Program
Write a program that will open a text file and extract each line within that file. As eaclh As each line is extracted from the first file, extract each word from the line and save After the entire line is saved to the second file, process the next line in the first file Keep processing lines until there are no more in the first text file. For example, if the first text file contains the following: Please do not feed your fingertips to the Wolverines. Do not feed the Badgers. Then the second file will contain: Wolverines, the to fingertips your feed not do Please Badgers, the feed not DoExplanation / Answer
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ReverseLines {
public static void writeOutput(String words[], int index, BufferedWriter bw) throws IOException{
if(index < 0) // wrote all words in file
return;
//write current word in file with single space
bw.write(words[index]+" ");
writeOutput(words, index-1, bw); // recursively calling for other words
}
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter input file name: ");
String inputFile = sc.next();
System.out.print("Enter output file name: ");
String outputFile = sc.next();
FileReader fr = new FileReader(inputFile);
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter(outputFile);
BufferedWriter bw = new BufferedWriter(fw);
String line;
//reading each line
while((line = br.readLine()) != null){
//splitting each line by space
String words[] = line.split("\s+");
// writing words in reverse order in file
writeOutput(words, words.length-1, bw);
//writing new line after current line
bw.newLine();
}
bw.close();
fr.close();
fw.close();
fr.close();
System.out.println("File writen successfully");
}
}
/*
Sample run:
Enter input file name: input.txt
Enter output file name: output.txt
File writen successfully
input.txt:
Please do not feed your fingertips to the Wolverines.
Do not feed the Badgers.
output.txt:
Wolverines. the to fingertips your feed not do Please
Badgers. the feed not Do
*/
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.