提示
Java IO FileInputStream 使用示例。@ermo
# FileInputStream 使用示例
来看一个从文件中读取数据的示例。
/**
* filepath
*/
public static final String FILEPATH = "src/main/resources/name.txt";
/**
* Read file text by FileInputStream.
*
* @return text
*/
public static String read() {
try (FileInputStream fit = new FileInputStream(FILEPATH)) {
int c;
String str = "";
while ((c = fit.read()) != -1) {
str += (char) c;
}
return str;
} catch (IOException e) {
e.printStackTrace();
}
return "";
}
/**
* Main method.
*
* @param args args
*/
public static void main(String[] args) {
System.out.println(read());
}
程序执行前应该创建 src/main/resources/name.txt
该文件,否则会抛出 FileNotFoundException
异常,文件内对应的内容为 You can't lose if you don't play.
。
try-with-resources
是 JDK7 的语法,将需要关闭的流放到 try
后的括号中,多个流使用 ;
隔开,程序读取完流中的数据后会自动关闭并释放资源,可以省去很多冗余的流关闭代码。
FileInputStream
常用的构造方法有:
// 通过文件名获取 FileInputStream 对象,文件名不存在时会抛出 FileNotFoundException 异常
public FileInputStream(String name) throws FileNotFoundException
// 通过文件对象 FileInputStream 对象,文件不存在时会抛出 FileNotFoundException 异常
public FileInputStream(File file) throws FileNotFoundException
来看一个通过 FileInputStream(File file)
构造 FileInputStream
的例子:
/**
* filepath
*/
public static final String FILEPATH = "src/main/resources/name.txt";
public static String readFromFile() {
FileInputStream in = null;
try {
File file = new File(FILEPATH);
in = new FileInputStream(file);
int c;
String data = "";
while ((c = in.read()) != -1) {
data += (char) c;
}
return data;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return "";
}
创建 FileInputStream
流后,通过 read()
方法读取文件内容,read()
方法返回类型为 int
,范围在0~255之间,内容读取结束后,将返回-1。
本次示例使用传统的流关闭方式,服务器的资源是有限的,因此释放流的方法 close()
应当放在 finally
语句块内。
read()
方法还有其他重载方法:
public int read(byte b[]) throws IOException
public int read(byte b[], int off, int len) throws IOException
read(byte b[])
可以将文件中的数据读取到一个 byte
数组中,从流中读取到的第一个字节存放于 b[0]
,第二个字节存放于 b[1]
,以此类推。
read(byte b[], int off, int len)
同样可以将流中的数据读取到 byte
数组中,读取到第一个字节存放于 b[off]
中,最多读取 len
个字节。
流读取完毕后,应该调用 close()
方法:
public void close() throws IOException
其他常用方法:
方法 | 描述 |
---|---|
public int available() throws IOException | 获取可读取字节的数量 |
public long skip(long n) throws IOException | 跳过流中 n 个字节 |
public FileChannel getChannel() | 返回与 InputStream 关联的 FileChannel 对象 |