Question

I've tried several things to open a text file that my program uses to display a map in a map creator. Everything works except that if I choose a text file, I get "null" as string. I don't know how it gets null, because the file exists (and I checked it before loading it)

Here my 2 code blocks for both tries:

public String OpenText(){
    String str = null;

    JFileChooser fc = new JFileChooser();

    int returnVal = fc.showOpenDialog(null);

    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = fc.getSelectedFile();
        System.out.println("Opening: " + file.getName() + ". " + "Path: "+file.getPath());
        if(new File(file.getPath()).exists()){
            try {
                System.out.println("File Exists.");
                /*FileReader fr = new FileReader(file);
                BufferedReader br = new BufferedReader(fr);

                StringBuilder sb = new StringBuilder();
                while((str = br.readLine())!= null){
                    sb.append(str);
                }
                */
                StringBuilder sb = new StringBuilder();
                Scanner input = new Scanner(file);
                while(input.hasNext()){
                    sb.append(input.nextLine());
                    sb.append("\n");
                }


            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    } else {
        System.out.println("Open command cancelled by user.");
    }
    System.out.println(str);
    return str;
}

The code gave at both the first attempt and the second attempt "null" as return.

I know the first code works since I use it to save my settings. But I also tried it with a Scanner.

Extra info: The file I try to open HAS text in it. I tried different text files.

Was it helpful?

Solution

Im following your case.
I tried as below and it works with text file (txt)

 StringBuilder sb = new StringBuilder();
 Scanner input = new Scanner(file);
 while(input.hasNext()){
    sb.append(input.nextLine());
    sb.append("\n");
    }
 str = sb.toString(); <-- Did you miss it?
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top