Question

Write a method in JAVA for accepting a text file as input and If the file...

Write a method in JAVA for accepting a text file as input and

If the file is of type .txt, then calculate and return the number of words in that txt file.

If the file is of type .csv, then return the number of rows and number of columns in that csv file.

If the file is of any other type, then return a message stating that file type is not supported.

Note: Use StringBuilder wherever applicable.

0 0
Add a comment Improve this question Transcribed image text
Answer #1


import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class FileStats {
   public static void main(String[] args) throws Exception {
       Scanner sc = new Scanner(System.in);
       System.out.println("Enter filename: ");
       String n = sc.next();
       System.out.println(getStats(n));
   }

   public static String getStats(String name) throws Exception {
       BufferedReader br = new BufferedReader(new FileReader(name));
       if (name.endsWith("txt")) {
           int wordCount = 0, lineCount = 0, charCount = 0;
           String line = br.readLine();
           while (line != null) {
               lineCount++;
               String arr[] = line.split("\\s");
               wordCount += arr.length;
               line = br.readLine();
           }
           return "The file " + name + " has words : " + wordCount;
       } else if (name.endsWith("csv")) {
           int cols = 0, rows = 0;
           String line = br.readLine();
           String arr[] = line.split(",");
           cols += arr.length;
           while (line != null) {
               rows++;
               line = br.readLine();
           }
           return "The file " + name + " has rows : " + rows + " and cols: " + cols;
       } else {
           return "file type is not supported";
       }
   }
}

<terminated > FileStats (2) [Java Application) C:\Progra Enter filename: input.txt The file input.txt has words : 10

Note : Please comment below if you have concerns. I am here to help you

If you like my answer please rate and help me it is very Imp for me

Add a comment
Know the answer?
Add Answer to:
Write a method in JAVA for accepting a text file as input and If the file...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT