File Information Lab Write a program that asks the user for a file name (or path
ID: 3538211 • Letter: F
Question
File Information Lab
Write a program that asks the user for a file name (or path). Your program should then open that specific file. (Assume the file will be .txt). Your program should then calculate the following information based on the specified text file:
%u3000
1. The number of lines in the file
2. The total number of words in the file
3. The number of characters in the file (not including spaces)
Once the information is calculated, print the data to the screen and also to a new file called results.txt.
Explanation / Answer
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication8;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
/**
*
* @author Admin
*/
public class JavaApplication8 {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO code application logic here
System.out.println("Enter the file name");
Scanner in = new Scanner(System.in);
String input = in.nextLine();
BufferedReader br = null;
br = new BufferedReader(new FileReader(input));
String line;
int noline = 0,nochar = 0,noword = 0;
while((line = br.readLine()) != null){
noline++;
for(char c:line.toCharArray()){
if(c != ' ')
nochar++;
}
noword += line.split(" ").length;
}
br.close();
String output = "No of lines "+noline+" No of words "+noword+" No of characters "+nochar;
FileWriter fw = new FileWriter("result.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(output);
bw.close();
System.out.println(output);
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.