首页 文章

从文件而不是单词加载数字

提问于
浏览
2
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();
    }
}

当它运行时,它不是放置文件中的正确单词,而是放置与单词无关的随机数字 . 我怎样才能解决这个问题?

4 回答

  • 0

    使用JTextComponent API提供的read()方法:

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

    您可能在二进制模式下读取文本文件( "test.txt" )(使用 FileInputStream.get ) .

    我建议你使用一些 ReaderScanner .

    例如,尝试以下方法:

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

    顺便说一下,你可能想用StringBuilder Build 字符串,最后做 textarea.setText(stringbuilder.toString()) .

  • 0

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

    从此输入流中读取一个字节的数据 .

    返回类型是int,而不是char或者其他东西 .

    所以aioobe说的是这样的 .

  • 0

    未经测试但您应该能够将字节(整数)转换为字符:

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

    然而,aioobe的答案可能仍然更好 .

相关问题