【字节流的写入方式】:
这里的close()只有关闭资源的作用,没有刷新作用。因为字节单位已经很小了,不需要经过中间处理,直接存入内存,所以不用刷新。
public static void writeFile() throws IOException{
FileOutputStream fos=new FileOutputStream("fos.txt");
fos.write("abcde".getBytes());
fos.close();
}
【字节流的读取方式】:
方式一:一个字节一个字节的读取。
方式二:利用缓冲数组存储起来,一次性打印。(数组长度为自定义)
方式三:利用缓冲数组存储起来,一次性打印。(数组长度为文件字节数)
/*方式一*/
public static void readFile_1() throws IOException{
FileInputStream fis=new FileInputStream("hhh.txt");
int ch=0;
while((ch=fis.read())!=-1){
System.out.println((char)ch);
}
fis.close();
}
/*方式二*/
public static void readFile_2() throws IOException{
FileInputStream fis=new FileInputStream("hhh.txt");
byte[] buf=new byte[1024];
int len=0;
while((len=fis.read(buf))!=-1){
System.out.println(new String(buf,0,len));
}
fis.close();
}
/*方式三*/
public static void readFile_3() throws IOException{
FileInputStream fis=new FileInputStream("hhh.txt");
int len=fis.available();
byte[] buf=new byte[len];
fis.read(buf);
System.out.println(new String(buf));
fis.close();
}
【示例】:
读取文件hhh.txt:

【输出】:
方式一对应:

方式二对应:
![]()
方式三对应:
博客介绍了字节流的读写方式。写入时,close()仅关闭资源,因字节单位小无需刷新。读取有三种方式,一是逐字节读取,二是用自定义长度缓冲数组存储后一次性打印,三是用与文件字节数相同的缓冲数组存储后一次性打印,还给出读取文件的示例。
1046

被折叠的 条评论
为什么被折叠?



