Question

In: Computer Science

Java Code Question: The program is supposed to read a file and then do a little...

Java Code Question:
The program is supposed to read a file and then do a little formatting and produce a new txt file. I have that functionality down.

My problem is that I also need to get my program to correctly identify if a file is empty, but so far I've been unable to. Here is my program in full:

import java.io.*;

import java.util.Scanner;

public class H1_43 {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter java file: ");

String fileName = scanner.nextLine();

if (fileName.isEmpty()) {

System.out.println("This is an empty file");

} else {

try {

Scanner fileReader = new Scanner(new File(fileName));

PrintWriter printWriter = new PrintWriter(new FileWriter(fileName + ".txt"));

int lineNumber = 1;

while (fileReader.hasNextLine()) {

String line = fileReader.nextLine();

printWriter.printf("[%03d]", lineNumber++);

printWriter.println(line);

printWriter.flush();

}

fileReader.close();

printWriter.close();

} catch (FileNotFoundException e) {

System.out.println("Error: Unable to open/read data from file: " + fileName);

System.exit(0);

} catch (IOException e) {

System.out.println("Error: Unable to open/write data to file: " + fileName);

System.exit(0);

}

System.out.println("File generated successfully.");

}

}

}

Solutions

Expert Solution

Answer:

Edited code is as below: You were checking the length of the string (file name) that is entered by the user empty or not, while you have to first read the file then empty test.

I have edited the code at two place only. Please check commented line.

import java.io.*;
import java.util.Scanner;
class Main
{
  public static void main(String[] args) 
  {
    Scanner scanner = new Scanner(System.in);
    System.out.print("Enter java file: ");
    String file = scanner.nextLine();
    //To read a file
    File fileName = new File(file);
      try 
      {
        Scanner fileReader = new Scanner(new File(file));
        if (!fileReader.hasNextLine())
        {
          System.out.println("This is an empty file");
        } 
        else 
        {
          PrintWriter printWriter = new PrintWriter(new FileWriter(fileName + ".txt"));
          int lineNumber = 1;
          while (fileReader.hasNextLine()) 
          {
            String line = fileReader.nextLine();
            printWriter.printf("[%03d]", lineNumber++);
            printWriter.println(line);
            printWriter.flush();
          }
          fileReader.close();
          printWriter.close();
          System.out.println("File generated successfully.");
        }
        
      } 
      catch (FileNotFoundException e) 
      {
        System.out.println("Error: Unable to open/read data from file: " + fileName);
        System.exit(0);
      } 
      catch (IOException e) 
      {
        System.out.println("Error: Unable to open/write data to file: " + fileName);
        System.exit(0);
      }
    }
}

Please give thumbsup, or do comment in case of any query. Thanks.


Related Solutions

You are supposed to write Java program for the following questions. For every question, do provide...
You are supposed to write Java program for the following questions. For every question, do provide at least THREE (3) different test cases. Question 1 Modify question 3 of Assignment 1 to accept a telephone number with any number of letters. The output should display a hyphen after the first 3 digits and subsequently a hyphen (-) after every four digits. Also, modify the program to process as many telephone numbers as the user wants.
Using java, I need to make a program that reverses a file. The program will read...
Using java, I need to make a program that reverses a file. The program will read the text file character by character, push the characters into a stack, then pop the characters into a new text file (with each character in revers order) EX: Hello World                       eyB       Bye            becomes    dlroW olleH I have the Stack and the Linked List part of this taken care of, I'm just having trouble connecting the stack and the text file together and...
Please write a java program to write to a text file and to read from a...
Please write a java program to write to a text file and to read from a text file.
Using JAVA The following code is able to read integers from a file that is called...
Using JAVA The following code is able to read integers from a file that is called "start.ppm" onto a 3d array called "startImage". Implement the code by being able to read from another file (make up any file name) and save the data onto another 3d array lets say you call that array "finalImage". The purpose of this will be to add both arrays and then get the average Save the average onto a separte 3darray,lets say you call it...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one...
JAVA Assignment: Project File Processing. Write a program that will read in from input file one line at a time until end of file and output the number of words in the line and the number of occurrences of each letter. Define a word to be any string of letters that is delimited at each end by either whitespace, a period, a comma or the beginning or end of the line. You can assume that the input consists entirely of...
Java question- Write a java program to process the number.txt file. Then count the numbers and...
Java question- Write a java program to process the number.txt file. Then count the numbers and calculate the total average, even numbers average, odd number average, then print the corresponding information. The result should be displayed in the following format there are XX numebers in the file there are xx even numbers there are xx odd numbers the total number average is xx the odd number average is xx the even number average is xx I am having trouble using...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the...
Write a Java program to read in words from the given file “word.txt”. a. Prompt the user for two words b. Print out how many words in the file fall between those words c. If one of the two words is not contained in the file, print out which word is not found in the file d. If both words are not found in the file, print out a message e. Sample output: Please type in two words: hello computer...
I need to write a java program (in eclipse) that will read my text file and...
I need to write a java program (in eclipse) that will read my text file and replace specific placeholders with information provided in a second text file. For this assignment I am given a text file and I must replace <N>, <A>, <G>, with the information in the second file. For example the information can be John 22 male, and the template will then be modified and saved into a new file or files (because there will be multiple entries...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional...
Write a program in Java to: Read a file containing ones and zeros into a two-dimensional int array. Your program must (1) read the name of the file from the command-line arguments, (2) open the file, (3) check that each line has the same number of characters and (4) check that the only characters in a line are ones and zeros. If there is no such command-line argument or no such file, or if any of the checks fail, your...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided...
Write a Java program to read in the 10 numbers in the example file Book1.csv provided above. The program should sum all the numbers, find the lowest number, find the highest number, and computer the average. Upon completion of the processing, the program should write a new text file named stats.txt with the information found in the following format where xxx represents a number calculated above. The sum of the numbers is: xxx The lowest number is: xxx The highest...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT