Java inputStream类的文件读取
读取步骤可以分为四步:
1. 使用File类读取文件
File src = new File("C:\\Users\\Administrator\\eclipse-workspace\\Test\\abc.txt");
2. 创建流,利用inputstream的子类FileInputStream读取文件
InputStream is = FileinputStream(src);
3. 操作流
int temp;
while ((temp = is.read()) != -1)
{
System.out.print((char) temp);
}
4. 关闭释放流
is.close();
整体代码
package test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class TestInputStream {
public static void main(String[] args) throws IOException {
// System.out.println(System.getProperty("usr.dir"));
// 读取文件
File src = new File("C:\\Users\\Administrator\\eclipse-workspace\\Test\\abc.txt");
// 创建流
InputStream is = null;
try {
is = new FileInputStream(src);
// 操作流
int temp;
while ((temp = is.read()) != -1) {
System.out.print((char) temp);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
// 释放流
is.close();
}
}
}