Crislips
Crislips

Reputation: 460

Reading a text file to a string ALWAYS results in empty string?

For the record, I know that reading the text file to a string does not ALWAYS result in an empty string, but in my situation, I can't get it to do anything else.

I'm currently trying to write a program that reads text from a .txt file, manipulates it based on certain arguments, and then saves the text back into the document. No matter how many different ways I've tried, I can't seem to actually get text from .txt file. The string just returns as an empty string.

For example, I pass in the arguments "-c 3 file1.txt" and parse the arguments for the file (the file is always passed in last). I get the file with:

            File inputFile = new File(args[args.length - 1]);

When I debug the code, it seems to recognize the file as file1.txt and if I pass in the name of a different file, which doesn't exist, and error is thrown. So it is correctly recognizing this file. From here I have attempted every type of file text parsing I can find online, from old Java version techniques up to Java 8 techniques. None have worked. A few I've tried are:

String fileText = "";
        try {
            Scanner input = new Scanner(inputFile);
            while (input.hasNextLine()) {
                fileText = input.nextLine();
                System.out.println(fileText);
            }
            input.close();
        } catch (FileNotFoundException e) {
            usage();
        }

or

String fileText = null;
    try {
        fileText = new String(Files.readAllBytes(Paths.get(filename)), StandardCharsets.UTF_8);
    } catch (IOException e) {
        e.printStackTrace();
    }

I've tried others too. Buffered readers, scanners, etc. I've tried recompiling the project, I've tried 3rd party libraries. Still just getting an empty string. I'm thinking it must be some sort of configuration issue, but I am stumped.

For anyone wondering, the file seems to be in the correct place, when I reference the wrong location an exception is thrown. And the file DOES in fact have text in it. I've quadruple checked.

Upvotes: 1

Views: 1808

Answers (2)

gil.fernandes
gil.fernandes

Reputation: 14621

My suggestion would be to create a method for reading the file into a string which throws an exception with a descriptive message whenever an unexpected state is found. Here is a possible implementation of this idea:

public static String readFile(Path path) {
    String fileText;
    try {
        if(Files.size(path) == 0) {
            throw new RuntimeException("File has zero bytes");
        }
        fileText = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        if(fileText.trim().isEmpty()) {
            throw new RuntimeException("File contains only whitespace");
        }
        return fileText;
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

This method checks 3 anomalies:

  1. File not found
  2. File empty
  3. File contains only spaces

Upvotes: 0

Thomas Behr
Thomas Behr

Reputation: 896

Even though your first code snippet might read the file, it does in fact not store the contents of the file in your fileText variable but only the file's last line. With

fileText = input.nextLine();

you set fileText to the contents of the current line thereby overwriting the previous value of fileText. You need to store all the lines from your file. E.g. try

static String read( String path ) throws IOException {
  StringBuilder sb = new StringBuilder();
  try (BufferedReader br = new BufferedReader(new FileReader(path))) {
    for (String line = br.readLine(); line != null; line = br.readLine()) {
      sb.append(line).append('\n');
    }
  }
  return sb.toString();
}

Upvotes: 2

Related Questions