常用方法:
available():返回下一次对此输入流调用的方法可以不受阻塞地从此输入流读取的估计剩余字节数
close():关闭文件输入流并释放与此流有关的所有系统资源
getChannel():返回与此文件输入流有关的唯一FileChannel对象
read():从此输入流中读取一个数据字节
read(byte[] b):从此输入流中将最多b.length个字节的数据读入一个byte数组中
read(byte[] b,int off,int len):从此输入流中将最多len个字节的数据读入到一个byte数组中
skip(long n):从输入流中跳过并丢弃n个字节的数据
import java.io.FileInputStream;
import java.io.IOException;
public class Study {
@SuppressWarnings({"all"})
public static void main(String[] args) {
readFile1();
}
public static void readFile1(){
String filePath = "d:\\hello.txt";
FileInputStream fileInputStream = null;
int read;
byte[] readBuff = new byte[8];
int readLen;
try {
fileInputStream = new FileInputStream(filePath);
//read()从该输入流读取一个字节的数据,如果没有输入可用,此方法将阻止
//如果返回-1表示文件读取完毕
while((read = fileInputStream.read()) != -1){
System.out.print((char) read);
}
//read(byte[] b)从该输入流读取最多b.length字节的数据到字节数组,此方法将阻塞,直到某些输入可用
//如果返回-1,表示读取结束,如果读取正常,返回实际读取的字节数
while ((readLen = fileInputStream.read(readBuff)) != -1){
String string = new String(readBuff, 0, readLen);
System.out.print(string);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭文件流,释放资源
try {
if (fileInputStream != null)
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
FileOutputStream:
write(int b):将指定字节写入此文件输出流
write(byte[] b):将b.length个字节从指定byte数组写入此文件输出流中
write(byte[] b,int off,int len):将指定byte数组中从偏移量off开始的len个字节写入此文件输出流
public class Study {
@SuppressWarnings({"all"})
public static void main(String[] args) {
writeFile();
}
public static void writeFile(){
String filePath = "d:\\a.txt";
FileOutputStream fileOutputStream = null;
try {
//1.new FileOutputStream(filePath)创建方式,当写入内容时会覆盖原来的内容
//2.new FileOutputStream(filePath,true)创建方式,当写入内容时会追加到文件后面
fileOutputStream = new FileOutputStream(filePath,true);
//fileOutputStream.write('h');//char->int
String s = "hello,world";
//s.getBytes()将字符串转成字节数组
fileOutputStream.write(s.getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (fileOutputStream != null)
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}