从文件加载数字而不是单词
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();
}
}
当它运行时,它不是放置文件中的正确单词,而是放置与单词无关的随机数。我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能正在以二进制模式读取文本文件 (
"test.txt"
)(使用FileInputStream.get
)。我建议您使用一些
Reader
或Scanner
。例如,尝试以下操作:
顺便说一句,您可能想使用
StringBuilder
并最后执行textarea.setText(stringbuilder.toString())
。You're presumably reading a text file (
"test.txt"
) in binary mode (usingFileInputStream.get
).I suggest you use some
Reader
or aScanner
.Try the following for instance:
Btw, you probably want to build up the string using a
StringBuilder
and dotextarea.setText(stringbuilder.toString())
in the end.使用 JTextComponent API 提供的 read() 方法:
Use the read() method provided by the JTextComponent API:
http://download.oracle .com/javase/6/docs/api/java/io/FileInputStream.html#read%28%29
并且返回类型是int,而不是char之类的。
所以就照aioobe说的做吧。
http://download.oracle.com/javase/6/docs/api/java/io/FileInputStream.html#read%28%29
and the return type is int, not char or something.
So do what aioobe said.
未经测试,但您应该也能够将字节(整数)转换为字符:
但是,aioobe 的答案可能仍然更好。
Not tested but you should be able to cast the byte (integer) to a character as well:
However, aioobe's answer is probably still better.