【问题标题】:Loading Numbers from a File Instead of Words从文件中加载数字而不是单词
【发布时间】:2011-08-30 09:09:08
【问题描述】:
包 jtextareatest; 导入 java.io.FileInputStream; 导入 java.io.IOException; 导入 javax.swing.*; 公共类 Jtextareatest { 公共静态 void main(String[] args) 抛出 IOException { FileInputStream in = new FileInputStream("test.txt"); JFrame frame = new JFrame("WHAT??"); frame.setSize(640, 480); JTextArea textarea = new JTextArea(); frame.add(textarea); 诠释 c; 而 ((c = in.read()) != -1) { textarea.setText(textarea.getText() + Integer.toString(c)); } frame.setVisible(true); 附寄(); } }

运行时,它不会放置文件中的正确单词,而是放置与单词无关的随机数。我该如何解决这个问题?

【问题讨论】:

  • 如果我将“test”写到 test.txt 并运行你的程序,它会产生 116 101 115 116 10 粘合在一起。这些数字是您要求的 ascii 值(c=in.read 读取字节,但返回整数,以便能够返回 -1 作为错误指示符,不是吗?您应该改用扫描仪。跨度>
  • test.txt的编码是什么?

标签: java swing file io


【解决方案1】:

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

我建议你使用一些ReaderScanner

试试下面的例子:

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

顺便说一句,您可能想使用StringBuilder 构建字符串,最后使用textarea.setText(stringbuilder.toString())

【讨论】:

    【解决方案2】:

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

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

    而且返回类型是int,不是char什么的。

    照着aioobe说的做吧。

    【讨论】:

      【解决方案3】:

      未经测试,但您应该也可以将字节(整数)转换为字符:

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

      不过,aioobe 的回答可能还是更好。

      【讨论】:

        【解决方案4】:

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

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

        【讨论】:

          猜你喜欢
          • 2011-01-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-04
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多