最近做了一个和文件读写相关的需求,做的过程中发现IO流相关的知识总是忘记,,所以这里做一个读写文件基本操作的总结,如下所示,仅供参考~
1. 字节流读数据(一次读一个字节数据)
@Test
public void Test01() throws IOException {
FileInputStream fis = new FileInputStream(filePath);
int by;
while ((by=fis.read())!=-1) {
System.out.print((char)by);
}
fis.close();
}
2. 字节流读数据(一次读一个字节数组数据)
@Test
public void Test02() throws IOException {
FileInputStream fis = new FileInputStream(filePath);
byte[] bys = new byte[1024]; //1024及其整数倍
int len;
while ((len=fis.read(bys))!=-1) {
System.out.print(new String(bys,0,len));
}
fis.close();
}
3. 字节流写数据
@Test
public void Test03() throws IOException {
FileOutputStream fos = new FileOutputStream(filePath);
// fos.write(97);
fos.write("abcdev".getBytes());
fos.write("rn".getBytes()); //换行
fos.write("abcdev".getBytes());
fos.close();
}
4. 字符流读数据
@Test
public void Test04() throws IOException {
InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath));
char[] chs = new char[1024];
int len;
while ((len = isr.read(chs)) != -1) {
System.out.print(new String(chs, 0, len));
}
isr.close();
}
5. 字符流写数据
@Test
public void Test05() throws IOException {
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath));
osw.write("abcde", 1, 3);
osw.close();
}
常用的IO流总结如下:
字节流和字符流其实在使用上很相似,只是字节流常用于操作普通的文本,而字符流优先操作图片视频等文件,而字节流又称为“万能流”。 同样缓冲流也很相似,主要的目的是为了提高操作效率!以上都是读写文件的部分基本操作,其他的方法也都类同,可以查阅对象的API对应使用



