java IO完整版学习笔记

原文出处:http://developer.51cto.com/art/201109/292225.htm

--->删除文件
# String fileName="D:"+File.separator+"hello.txt";
# File f=new File(fileName);
# if(f.exists()){
# f.delete();
# }else{
# System.out.println("文件不存在");
# }
f.mkdir();
# File f=new File(fileName);
# File[] str=f.listFiles(); //f.list

if(temp.isFile())
if(temp.isDirectory())
续传文件
# RandomAccessFile demo=new RandomAccessFile(f,"rw");
# demo.writeBytes("asdsad");
字节流 向文件中写入字符串
OutputStream out =new FileOutputStream(f); //追加;new FileOutputStream(f,true);
读文件
FileInputStream input = new FileInputStream(temp);
byte[] b = new byte[1024 * 5];
while ( (len = input.read(b)) != -1)

字符流
#写 Writer out =new FileWriter(f); //追加 new FileWriter(f,true);
# String str="hello";
# out.write(str);

#读 char[] ch=new char[100];
# Reader read=new FileReader(f);
# int count=read.read(ch);

将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。你就会发现使用字节流的话,文件中已经存在内容,但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。

使用字节流好还是字符流好呢? 答案是字节流。首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的 字符流开发方便

整个IO类中除了字节流和字符流还包括字节和字符转换流。
OutputStreramWriter将输出的字符流转化为字节流
InputStreamReader将输入的字节流转换为字符流
但是不管如何操作,最后都是以字节的形式保存在文件中的。将字节输出流转化为字符输出流

Writer out=new OutputStreamWriter(new FileOutputStream(file)); //将输出的字符流转化为字节流

Reader read=new InputStreamReader(new FileInputStream(file));
# char[] b=new char[100];
# int len=read.read(b);

以内容为输出输入目的地
ByteArrayInputStream 主要将内容写入内容
ByteArrayOutputStream 主要将内容从内存输出

管道流主要可以进行两个线程之间的通信。
PipedOutputStream 管道输出流
PipedInputStream 管道输入流

# BufferedReader buf = new BufferedReader(
# new InputStreamReader(System.in));

Scanner的小例子,从键盘读数据

SequenceInputStream主要用来将2个流合并在一起,比如将两个txt中的内容合并为另外一个txt。下面给出一个实例:
# SequenceInputStream sis = new SequenceInputStream(input1, input2);
# int temp = 0;
# while((temp = sis.read()) != -1){
# output.write(temp);
# }

文件压缩 ZipOutputStream类
# ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
# zipFile));
# zipOut.putNextEntry(new ZipEntry(file.getName()));
# // 设置注释
# zipOut.setComment("hello");
# int temp = 0;
# while((temp = input.read()) != -1){
# zipOut.write(temp);
# }

对象序列化就是把一个对象变为二进制数据流的一种方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值