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

in java (just a line of code will do) Your program will read in the text...
in java (just a line of code will do) Your program will read in the text file, word by word. You are to ignore leading and trailing punctuation and capitalization (i.e., "Castle", "castle?", and "CASTLE" are all equivalent to castle). Convert all words to lower case on input, or you can use case-insensitive comparisons - your choice. You will be putting the words into several implementations of linked lists and comparing the results. If, after trimming punctuation, a "word" consists...
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.
Write a Java program to read a set of integers from a file, dataX, and a...
Write a Java program to read a set of integers from a file, dataX, and a set of ranges from a second file, rangeX, and, for each range [a, b] in rangeX, report the SUM of all the integers in dataX which are in the range [a, b]. As the integers are read from file dataX, insert them in a binary search tree. After all the integers have been inserted into the binary search tree, read the ranges from file...
Write a java program that will read a file called stateinfo.txt and will store the information...
Write a java program that will read a file called stateinfo.txt and will store the information of the file into a map. The stateinfo.txt file contains the names of some states and their capitals. The format of stateinfo.txt file is as follows. State                Capital ---------                         ----------- NSW               Sydney VIC                 Melbourne WA                 Perth TAS                 Tasmania QLD                Brisbane SA                   Adelaide The program then prompts the user to enter the name of a state. Upon receiving the user input, the program should...
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...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT