Search code examples
javaswingfileio

Loading Numbers from a File Instead of Words


package jtextareatest;

import java.io.FileInputStream;
import java.io.IOException;
import javax.swing.*;

public class Jtextareatest {
    public static void main(String[] args) throws IOException {
        FileInputStream in = new FileInputStream("test.txt");
        
        JFrame frame = new JFrame("WHAT??");
        frame.setSize(640, 480);
        JTextArea textarea = new JTextArea();
        frame.add(textarea);
        
        int c;
        while ((c = in.read()) != -1) {
            textarea.setText(textarea.getText() + Integer.toString(c));
        }
        
        frame.setVisible(true);
        in.close();
    }
}

When this runs, instead of placing the correct words from the file, it instead places random numbers that have no relevance to the words. How can I fix this?


Solution

  • You're presumably reading a text file ("test.txt") in binary mode (using FileInputStream.get).

    I suggest you use some Reader or a Scanner.

    Try the following for instance:

    Scanner scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNextInt())
        textarea.setText(textarea.getText() + scanner.nextInt());
    

    Btw, you probably want to build up the string using a StringBuilder and do textarea.setText(stringbuilder.toString()) in the end.