Java Programming (NetBeans IDE) Exercise 1 [FileReadWrite.java] Download the fil
ID: 3753512 • Letter: J
Question
Java Programming (NetBeans IDE)
Exercise 1 [FileReadWrite.java] Download the file WordsandLines.txt to your machine and place it in your project folder. Write a program to read the WordsandLines.txt file and count how many words and lines of text it contains. Then, the program should write the content of WordsandLines.txt to a new file LinesandWords.txt in the same folder but in reverse order (starting from the last word on the last line) Sample input Wordsandlines.txt This is a file that contains exactlx nine words! Oops, I mean eighteen And seven lines of text! Sample Output Standard Output Total word count 18 Total number of lines 6 Linesandwords.tct. txet fe senil neves dnA sdrow enin tcaxe niatnoc taht elif a i sihTExplanation / Answer
WordsAndLines.txt
This is a file
that contains
exactly
nine words!
Oops, I mean eighteen.
And seven lines of text!
______________
ReadFile.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ReadFile {
public static void main(String[] args) {
ArrayList<String> ar = new ArrayList<String>();
int cntWords=0,cntLines=0;
Scanner sc;
try {
// Opening the input file
sc = new Scanner(new File("WordsAndLines.txt"));
// Opening the output file
File f2 = new File("LinesAndWords.txt");
FileWriter fw = new FileWriter(f2);
// Reading the data from the input file and write the data to the
// output file
while (sc.hasNext()) {
String str = sc.nextLine();
if (!str.isEmpty())
{
str=str.trim();
String arr[]=str.split(" ");
cntWords+=arr.length;
cntLines++;
}
ar.add(str);
}
sc.close();
for (int i = ar.size()-1; i >=0; i--) {
String s=ar.get(i);
for(int j=s.length()-1;j>=0;j--)
{
fw.write(s.charAt(j));
}
fw.write(" ");
}
// closing the input file and output file
fw.close();
System.out.println("Total No of Words:"+cntWords);
System.out.println("Total No of Lines:"+cntLines);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
____________________
Output(Console):
Total No of Words:18
Total No of Lines:6
__________________
LinesAndWords.txt
!txet fo senil neves dnA
.neethgie naem I ,spoO
!sdrow enin
yltcaxe
sniatnoc taht
elif a si sihT
_______Could you plz rate me well.Thank You
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.