字符流:
2)字节数组读取
3)还是字节数组读取,但是用available()方法直接获取数组长度【使用时注意内存溢出问题】
FileReader
FileWriter
BufferedFileReader
BufferedFileWriter
字节流:
字节流不需要flush,但是仍然需要关闭流资源。
FileInputStream
FileOutputStream
BufferedInputStream
BufferedOutputStream
注意:单个字节读取时read()返回int实际上是在读取的byte上补位;write(int)实际上是把int的最低8位写入。
FileOutputStream:
write()方法接收byte数组,所以用字符串的getBytes()方法将String转成数组:
public static void writeFile() throws IOException
{
FileOutputStream fos = new FileOutputStream("x.txt");
fos.write("abcde.kihdsa\r\nsdhasdasd\r\n{}HH".getBytes()); //字符串转byte数组
fos.close();
}
FileInputStream:
三种读取方式:
1)单个字节读取
public static void readFile_1() throws IOException
{
FileInputStream fis = new FileInputStream("x.txt");
int num = 0;
while((num = fis.read()) != -1)
System.out.print((char)num); //打印在屏幕上,所以转为char
fis.close();
}
2)字节数组读取
public static void readFile_2() throws IOException
{
FileInputStream fis = new FileInputStream("x.txt");
byte[] b = new byte[1024];
int num = 0;
while((num = fis.read(b)) != -1)
System.out.print(new String(b,0,num));
fis.close();
}
3)还是字节数组读取,但是用available()方法直接获取数组长度【使用时注意内存溢出问题】
public static void readFile_3() throws IOException
{
FileInputStream fis = new FileInputStream("x.txt");
byte[] b = new byte[fis.available()];
fis.read(b);
System.out.print(new String(b));
fis.close();
}
}
BufferedInputStream
可以装饰InputStream类,自己写一个MyBufferedInputStream类:
import java.io.*;
class MyBufferedInputStream
{
private InputStream in;
private byte[] buf = new byte[1024];
private pos = 0,count = 0;
MyBufferedInputStream(InputStream in)
{
this.in = in;
}
public int myRead() throws IOException
{
if(count == 0)
{
count = in.read(buf);
if(count < 0)
return -1;
pos = 0;
byte b = buf[pos];
count--;
pos++;
return b&0xff; //byte转换成int缺位补0,以免11111111变成-1(11111111 11111111 11111111 11111111),而非255(00000000 00000000 00000000 11111111)
}
else if(count > 0)
{
byte b = buf[pos];
count--;
pos++;
return b&0xff; //byte转换成int缺位补0,以免11111111变成-1(11111111 11111111 11111111 11111111),而非255(00000000 00000000 00000000 11111111)
}
return -1;
}
public void myClose() throws IOException
{
in.close();
}
}