1
votes
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?

4
If I write "test" to test.txt, and run your program, it yields 116 101 115 116 10 glued together. These numbers are the ascii-values you asked for (c=in.read reads bytes, but returns ints, to be able to return a -1 as error-indicator, doesn't it? You should use a Scanner instead.user unknown
What is the encoding of test.txt?trashgod

4 Answers

6
votes

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.

0
votes

http://download.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read%28%29

Reads a byte of data from this input stream.

and the return type is int, not char or something.

So do what aioobe said.

0
votes

Not tested but you should be able to cast the byte (integer) to a character as well:

int c;
while ((c = in.read()) != -1)
{
    textarea.setText(textarea.getText() + Character.toString((char)c));
}

However, aioobe's answer is probably still better.

0
votes

Use the read() method provided by the JTextComponent API:

FileReader reader = new FileReader( "test.txt" );
BufferedReader br = new BufferedReader(reader);
textArea.read( br, null );
br.close();