0

ive tried many different things and this is the only thing that has worked with reading one line from a file so far...

try{

        FileInputStream fstream = new FileInputStream("./Saves/Body.sav");
        BufferedReader br = new BufferedReader(new InputStreamReader(infstream);
        String strLine;    
        while ((strLine = br.readLine()) != null)   {      
        System.out.println(strLine);
        w1.Body = strLine;
        }  
        in.close();
          }catch (Exception e){//Catch exception if any
        System.err.println("Error: " + e.getMessage());
        }

I am trying to create a load function so i can load text from a file onto a string onto a jTextArea... Without any sort of openfiledialog

4

3 に答える 3

5

I'd personally use Guava:

File file = new File("Saves", "Body.sav");
String text = Files.toString(file, Charsets.UTF_8);

That's assuming it's a UTF-8 file, of course. Adjust accordingly.

Your current code has a number of issues:

  • It creates a DataInputStream for no obvious reason
  • You probably don't gain much from using BufferedReader
  • You're not specifying the character encoding, so you're getting the platform default, implicitly, which is almost never a good idea.
  • You're closing in which is in the middle of the chain of inputs for some reason... I'd expect to close either br or fstream
  • You're only closing in if there's no exception (use a finally block or a try-with-resources statement if you're using Java 7)
  • You appear to have a field called Body, violating Java naming conventions
  • You're catching Exception rather than IOException - prefer to catch specific exceptions
  • You're "handling" the exception by effectively ignoring it, which is almost never appropriate. (The code which reads a file is very rarely the right code to decide what to do with an exception.)
于 2012-11-07T08:48:26.943 に答える
3

How do i read ... put in jTextArea?

Ignoring the entire middle of that statement, I suggest.

File file = new File("./Saves/Body.sav");
FileReader fileReader = new FileReader(file);
textArea.read(fileReader, file);
于 2012-11-07T09:20:26.567 に答える
1

You can use a StringBuilder (or the synchronized version StringBuffer) and keep appending strLine to it. Declare it this way:

StringBuilder s = new StringBuilder();

and in the while loop:

s.append(strLine + "\n");
于 2012-11-07T08:49:52.580 に答える