Write a program that asks a user for a file name and prints the number of charac
ID: 3808490 • Letter: W
Question
Write a program that asks a user for a file name and prints the number of characters, words (separated by whitespace), and lines in that file. Then, it replaces each line of the file with its reverse. For example, if the file contains the following lines (Test1.txt):
This is a test
Hi there
Output on the console:
Number of characters: 22
Number of words: 6
Number of lines: 2
Data written to the file (Test1.txt):
tset a si sihT
ereth iH
Save the source code in “FileReverseWord.java”. "Need a java program asap"
Explanation / Answer
FileReverseWord.java
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Scanner;
public class FileReverseWord{
public static void main(String[] args) throws FileNotFoundException {
Scanner scan = new Scanner(System.in);
System.out.println("Enter file name: ");
String fileName = scan.next();
StringBuffer finalsb = new StringBuffer();
File file = new File(fileName);
if(file.exists()){
int numberOfLines = 0;
int numberOfCharacters = 0;
int numberOfWords = 0;
Scanner scan1 = new Scanner(file);;
while(scan1.hasNextLine()){
StringBuffer sb = new StringBuffer();
String s = scan1.nextLine();
sb.append(s);
numberOfLines++;
numberOfCharacters = numberOfCharacters + s.length();
String words[] = s.split(" ");
numberOfWords = numberOfWords + words.length;
finalsb.append(sb.reverse());
finalsb.append(" ");
}
System.out.println("Number of characters: "+numberOfCharacters);
System.out.println("Number of words: "+numberOfWords);
System.out.println("Number of lines : "+numberOfLines);
PrintStream ps =new PrintStream(file);
ps.print(finalsb.toString());
ps.flush();
ps.close();
System.out.println("Data written to the file "+fileName);
}
else{
System.out.println("File does not exist");
}
}
}
Output:
Enter file name:
D:\Test1.txt
Number of characters: 22
Number of words: 6
Number of lines : 2
Data written to the file D:\Test1.txt
tset a si sihT
ereht iH
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.