请帮我解决这个问题。
A 有一个内容为“Thanh Le”的输入文件“Trial.txt”。
这是我在尝试从文件中读取时使用的函数:
public char[] importSeq(){
File file = new File("G:\\trial.txt");
char temp_seq[] = new char[100];
try{
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
int i = 0;
//Try to read all character till the end of file
while(dis.available() != 0){
temp_seq[i]=dis.readChar();
i++;
}
System.out.println(" imported");
} catch (FileNotFoundException e){
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}
return temp_seq;
}
主要功能:
public static void main(String[] args) {
Sequence s1 = new Sequence();
char result[];
result = s1.importSeq();
int i = 0;
while(result[i] != 0){
System.out.println(result[i]);
i++;
}
}
这是输出。
运行:
imported
瑨
慮
栠
汥
BUILD SUCCESSFUL (total time: 0 seconds)
最佳答案
老实说,这是一种将文本文件读入 char[]
的非常笨拙的方法。
这里有一个更好的例子,假设文本文件只包含 ASCII 字符。
File file = new File("G:/trial.txt");
char[] content = new char[(int) file.length()];
Reader reader = null;
try {
reader = new FileReader(file);
reader.read(content);
} finally {
if (reader != null) try { reader.close(); } catch (IOException ignore) {}
}
return content;
然后要打印 char[]
,只需执行以下操作:
System.out.println(content);
请注意,InputStream#available()
不一定会执行您所期望的操作。
另见:
关于java - println(char), 字符转成中文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3895656/