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.
Create a java program that has a code file with main() in it and another code...
Create a java program that has a code file with main() in it and another code file with a separate class. You will be creating objects of the class in the running program, just as the chapter example creates objects of the Account class. Your system handles employee records and processes payroll for them. Create a class called Employee that holds the following information: first name, last name, monthly salary, and sales bonus. The class should have all the gets...
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...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT