Java通过java.io.FileInputStream读取txt文本。
package com;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class TestIO {
public static void main(String[] args) {
FileInputStream in = null;
try {
in = new FileInputStream("test.txt");
int c;
c = in.read();
while (c != -1) {
System.out.print((char) c);
c = in.read();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.println(e.getMessage());
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
其中test.txt内为英文字符串,放在eclipse项目文件夹根目录下,对于中文需要做编码处理。
本文介绍了一个使用Java的FileInputStream类来读取TXT文件的例子。该示例展示了如何逐字符读取文件内容,并处理可能出现的FileNotFoundException和IOException。注意,对于中文内容的读取可能需要额外的编码处理。
305

被折叠的 条评论
为什么被折叠?



