In: Computer Science
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.");
}
}
}
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.