JAVA——IO整理

下文出处:http://blog.csdn.net/ilibaba/article/details/3955799

(三)Java IO 的一般使用原则 :  

一、按数据来源(去向)分类:

1 、是文件: FileInputStream, FileOutputStream, ( 字节流 )FileReader, FileWriter( 字符 )

2 、是 byte[] : ByteArrayInputStream, ByteArrayOutputStream( 字节流 )

3 、是 Char[]: CharArrayReader, CharArrayWriter( 字符流 )

4 、是 String: StringBufferInputStream, StringBufferOuputStream ( 字节流 )StringReader, StringWriter( 字符流 )

5 、网络数据流: InputStream, OutputStream,( 字节流 ) Reader, Writer( 字符流 )

二、按是否格式化输出分:

1 、要格式化输出: PrintStream, PrintWriter

三、按是否要缓冲分:

1 、要缓冲: BufferedInputStream, BufferedOutputStream,( 字节流 ) BufferedReader, BufferedWriter( 字符流 )

四、按数据格式分:

1 、二进制格式(只要不能确定是纯文本的) : InputStream, OutputStream 及其所有带 Stream 结束的子类

2 、纯文本格式(含纯英文与汉字或其他编码方式); Reader, Writer 及其所有带 Reader, Writer 的子类

五、按输入输出分:

1 、输入: Reader, InputStream 类型的子类

2 、输出: Writer, OutputStream 类型的子类

六、特殊需要:

1 、从 Stream 到 Reader,Writer 的转换类: InputStreamReader, OutputStreamWriter

2 、对象输入输出: ObjectInputStream, ObjectOutputStream

3 、进程间通信: PipeInputStream, PipeOutputStream, PipeReader, PipeWriter

4 、合并输入: SequenceInputStream

5 、更特殊的需要: PushbackInputStream, PushbackReader, LineNumberInputStream, LineNumberReader

决定使用哪个类以及它的构造进程的一般准则如下(不考虑特殊需要):

首先,考虑最原始的数据格式是什么: 原则四

第二,是输入还是输出:原则五

第三,是否需要转换流:原则六第 1 点

第四,数据来源(去向)是什么:原则一

第五,是否要缓冲:原则三 (特别注明:一定要注意的是 readLine() 是否有定义,有什么比 read, write 更特殊的输入或输出方法)

第六,是否要格式化输出:原则二 

*************************************************************************************************************************

下文出处:http://www.cnblogs.com/rollenholt/archive/2011/09/11/2173787.html

文件IO

案例详解

【案例1】创建一个新文件

import java.io.*;
class hello{
    public static void main(String[] args) {
        File f=new File("D:\\hello.txt");
        try{
            f.createNewFile();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【运行结果】:

程序运行之后,在 d 盘下会有一个名字为 hello.txt 的文件。


【案例2】File类的两个常量

import java.io.*;
class hello{
    public static void main(String[] args) {
        System.out.println(File.separator);
        System.out.println(File.pathSeparator);
    }
}

【运行结果】:

\

;

此处多说几句:

有些同学可能认为,我直接在windows下使用\进行分割不行吗?当然是可以的。

但是在linux下就不是\了。

所以,要想使得我们的代码跨平台,更加健壮,所以,大家都采用这两个常量吧,其实也多写不了几行。呵呵、
现在我们使用File类中的常量改写上面的代码:

import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        try{
            f.createNewFile();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【案例3】删除一个文件

/**
 * 删除一个文件
 * */
import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        if(f.exists()){
            f.delete();
        }else{
            System.out.println("文件不存在");
        }
         
    }
}

【案例4】创建一个文件夹

/**
 * 创建一个文件夹
 * */
import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator+"hello";
        File f=new File(fileName);
        f.mkdir();
    }
}

【运行结果】:

D 盘下多了一个 hello 文件夹

【案例5】列出指定目录的全部文件(包括隐藏文件)仅文件名:

/**
 * 使用list列出指定目录的全部文件
 * */
import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator;
        File f=new File(fileName);
        String[] str=f.list();
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }
}

但是使用list返回的是String数组,而且列出的不是完整路径,(仅显示文件名,无路径)

如果想列出完整路径的话,需要使用listFiles.他返回的是File的数组

列出指定目录的全部文件(包括隐藏文件)完整路径:
/**
 * 使用listFiles列出指定目录的全部文件
 * listFiles输出的是完整路径
 * */
import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator;
        File f=new File(fileName);
        File[] str=f.listFiles();
        for (int i = 0; i < str.length; i++) {
            System.out.println(str[i]);
        }
    }
}

【运行结果】:

D:\$RECYCLE.BIN

D:\360

【案例6】判断一个指定的路径是否为目录

/**
 * 使用isDirectory判断一个指定的路径是否为目录
 * */
import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator;
        File f=new File(fileName);
        if(f.isDirectory()){
            System.out.println("YES");
        }else{
            System.out.println("NO");
        }
    }
}

【案例7】搜索指定目录的全部内容

/**
 * 列出指定目录的全部内容
 * */
import java.io.*;
class hello{
    public static void main(String[] args) {
        String fileName="D:"+File.separator;
        File f=new File(fileName);
        print(f);
    }
    public static void print(File f){
        if(f!=null){
            if(f.isDirectory()){
                File[] fileArray=f.listFiles();
                if(fileArray!=null){
                    for (int i = 0; i < fileArray.length; i++) {
                        //递归调用
                        print(fileArray[i]);
                    }
                }
            }
            else{
                System.out.println(f);
            }
        }
    }
}

【案例8】使用RandomAccessFile写入文件

/**
 * 使用RandomAccessFile写入文件
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        RandomAccessFile demo=new RandomAccessFile(f,"rw");
        demo.writeBytes("asdsad");
        demo.writeInt(12);
        demo.writeBoolean(true);
        demo.writeChar('A');
        demo.writeFloat(1.21f);
        demo.writeDouble(12.123);
        demo.close();  
    }
}
注:如果你此时打开 hello txt 查看的话,会发现那是乱码。

字节流

【案例1】向文件中写入字符串

/**
 * 字节流
 * 向文件中写入字符串
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        OutputStream out =new FileOutputStream(f);
        String str="你好";
        byte[] b=str.getBytes();
        out.write(b);
        out.close();
    }
}

当然也可以一个字节一个字节的写。

/**
 * 字节流
 * 向文件中一个字节一个字节的写入字符串
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        OutputStream out =new FileOutputStream(f);
        String str="你好";
        byte[] b=str.getBytes();
        for (int i = 0; i < b.length; i++) {
            out.write(b[i]);
        }
        out.close();
    }
}

【案例2】向文件中追加新内容
OutputStream out =new FileOutputStream(f,true);
<pre name="code" class="java">out.write(b);
out.close();
 

/**
 * 字节流
 * 向文件中追加新内容:
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        OutputStream out =new FileOutputStream(f,true);
        String str="Rollen";
        //String str="\r\nRollen";  可以换行
        byte[] b=str.getBytes();
        for (int i = 0; i < b.length; i++) {
            out.write(b[i]);
        }
        out.close();
    }
}

【案例3】读取文件内容
InputStream in=new FileInputStream(f);
<pre name="code" class="cpp">in.read(b);
in.close();
 

/**
 * 字节流
 * 读文件内容
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        InputStream in=new FileInputStream(f);
        byte[] b=new byte[1024];
        in.read(b);
        in.close();
        System.out.println(new String(b));
    }
}
但是这个例子读取出来会有大量的空格,我们可以利用 in.read(b); 的返回值——读入的长度来设计程序。如下:
/**
 * 字节流
 * 读文件内容
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        InputStream in=new FileInputStream(f);
        byte[] b=new byte[1024];
        int len=in.read(b);
        in.close();
        System.out.println("读入长度为:"+len);
        System.out.println(new String(b,0,len));
    }
}

【案例4】读取文件内容缓冲数据空间,大小的问题

读者观察上面的例子可以看出,我们预先申请了一个指定大小的空间。

但是有时候这个空间可能太小,有时候可能太大,我们需要准确的大小,这样节省空间,那么我们可以这样干:

/**
 * 字节流
 * 读文件内容,节省空间
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        InputStream in=new FileInputStream(f);
        byte[] b=new byte[(int)f.length()];
        in.read(b);
        System.out.println("文件长度为:"+f.length());
        in.close();
        System.out.println(new String(b));
    }
}

【案例5】读取文件内容缓冲数据空间,大小的问题

细心的读者可能会发现,上面的几个例子都是在知道文件的内容多大,然后才展开的。

有时候我们不知道文件有多大,这种情况下,我们需要判断是否独到文件的末尾。

/**
 * 字节流
 *读文件
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        InputStream in=new FileInputStream(f);
        byte[] b=new byte[1024];
        int count =0;
        int temp=0;
        while((temp=in.read())!=(-1)){
            b[count++]=(byte)temp;
        }
        in.close();
        System.out.println(new String(b));
    }
}

注: 当独到文件末尾的时候会返回 -1. 正常情况下是不会返回 -1

字符流

【案例1】向文件中写入数据
Writer out =new FileWriter(f);
<pre name="code" class="java">out.write(str);
out.close();
 

现在我们使用字符流

/**
 * 字符流
 * 写入数据
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        Writer out =new FileWriter(f);
        String str="hello";
        out.write(str);
        out.close();
    }
}

其实这个例子上之前的例子没什么区别,只是你可以直接输入字符串,而不需要你将字符串转化为字节数组。

当你如果想往文件中追加内容的时候,可以使用将上面的声明out的哪一行换为:

Writer out =new FileWriter(f,true);

这样,当你运行程序的时候,会发现文件内容变为:

hellohello如果想在文件中换行的话,需要使用“\r\n

比如将str变为String str="\r\nhello";

这样文件追加的 str 的内容就会换行了。

【案例3】从文件中读内容
<span style="font-size:18px;">Reader read=new FileReader(f);
</span><pre name="code" class="cpp"><span style="font-size:18px;">int count=read.read(ch);
read.close();</span>
 

/**
 * 字符流
 * 从文件中读出内容
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        char[] ch=new char[100];
        Reader read=new FileReader(f);
        int count=read.read(ch);
        read.close();
        System.out.println("读入的长度为:"+count);
        System.out.println("内容为"+new String(ch,0,count));
    }
}
当然最好采用循环读取的方式,因为我们有时候不知道文件到底有多大。

/**
 * 字符流
 * 从文件中读出内容
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName="D:"+File.separator+"hello.txt";
        File f=new File(fileName);
        char[] ch=new char[100];
        Reader read=new FileReader(f);
        int temp=0;
        int count=0;
        while((temp=read.read())!=(-1)){
            ch[count++]=(char)temp;
        }
        read.close();
        System.out.println("内容为"+new String(ch,0,count));
    }
}

关于字节流和字符流的区别

实际上

字节流,不会用到缓冲区的,是对文件本身的直接操作

字符流,会用到缓冲区的,是通过缓冲区来操作文件

读者可以试着将上面的字节流和字符流的程序的最后一行关闭文件的代码注释掉,然后运行程序看看。

你就会发现

使用字节流的话,文件中已经存在内容,

但是使用字符流的时候,文件中还是没有内容的,这个时候就要刷新缓冲区。

使用字节流好还是字符流好呢?

答案是字节流。

首先因为硬盘上的所有文件都是以字节的形式进行传输或者保存的,包括图片等内容。

但是字符只是在内存中才会形成的,所以在开发中,字节流使用广泛。

文件的复制(没看懂作者要干嘛。。。)

下面我们使用程序来复制文件吧。

基本思路还是从一个文件中读入内容,边读边写入另一个文件,就是这么简单。、

首先编写下面的代码:

/**
 * 文件的复制
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        if(args.length!=2){
            System.out.println("命令行参数输入有误,请检查");
            System.exit(1);
        }
        File file1=new File(args[0]);
        File file2=new File(args[1]);
         
        if(!file1.exists()){
            System.out.println("被复制的文件不存在");
            System.exit(1);
        }
        InputStream input=new FileInputStream(file1);
        OutputStream output=new FileOutputStream(file2);
        if((input!=null)&&(output!=null)){
            int temp=0;
            while((temp=input.read())!=(-1)){
                output.write(temp);
            }
        }
        input.close();
        output.close();
    }
}

OutputStreramWriter 和InputStreamReader类

整个IO类中除了字节流和字符流还包括字节和字符转换流

OutputStreramWriter将输出的字符流转化为字节流——将一个字符流的输出对象,变为字节流的输出对象

InputStreamReader将输入的字节流转换为字符流——将一个字节流的输入对象,变为字符流的输入对象

但是不管如何操作,最后都是以字节的形式保存在文件中的。

【案例1】字节输出流转化为字符输出流

/**
 * <code class="java preprocessor">将字节输出流转化为字符输出流</code>
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName= "d:"+File.separator+"hello.txt";
        File file=new File(fileName);
        Writer out=new OutputStreamWriter(new FileOutputStream(file));//字节流转换为字符流
        out.write("hello");//使用字符流输出
        out.close();
    }
}

【案例2】将字节输入流变为字符输入流

/**
 * 将字节输入流变为字符输入流
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String fileName= "d:"+File.separator+"hello.txt";
        File file=new File(fileName);
        Reader read=new InputStreamReader(new FileInputStream(file));
        char[] b=new char[100];
        int len=read.read(b);
        System.out.println(new String(b,0,len));
        read.close();
    }
}

内存IO

前面列举的输出输入都是以文件进行的,现在我们以内容为输出输入目的地,使用内存操作流

ByteArrayInputStream 主要将内容写入内容

ByteArrayOutputStream  主要将内容从内存输出

【案例1】使用内存操作流将一个大写字母转换成小写字母

/**
 * 使用内存操作流将一个大写字母转化为小写字母
 * */
import java.io.*;
class hello{
    public static void main(String[] args) throws IOException {
        String str="ROLLENHOLT";
        ByteArrayInputStream input=new ByteArrayInputStream(str.getBytes());
        ByteArrayOutputStream output=new ByteArrayOutputStream();
        int temp=0;
        while((temp=input.read())!=-1){
            char ch=(char)temp;
            output.write(Character.toLowerCase(ch));
        }
        String outStr=output.toString();
        input.close();
        output.close();
        System.out.println(outStr);
    }
}

内容操作流一般使用来生成一些临时信息采用的,这样可以避免删除的麻烦。

管道流

管道流主要可以进行两个线程之间的通信。

PipedOutputStream 管道输出流

PipedInputStream 管道输入流

【案例1】验证管道流

/**
 * 验证管道流
 * */
import java.io.*;
 
/**
 * 消息发送类
 * */
class Send implements Runnable{
    private PipedOutputStream out=null;
    public Send() {
        out=new PipedOutputStream();
    }
    public PipedOutputStream getOut(){
        return this.out;
    }
    public void run(){
        String message="hello , Rollen";
        try{
            out.write(message.getBytes());
        }catch (Exception e) {
            e.printStackTrace();
        }try{
            out.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
/**
 * 接受消息类
 * */
class Recive implements Runnable{
    private PipedInputStream input=null;
    public Recive(){
        this.input=new PipedInputStream();
    }
    public PipedInputStream getInput(){
        return this.input;
    }
    public void run(){
        byte[] b=new byte[1000];
        int len=0;
        try{
            len=this.input.read(b);
        }catch (Exception e) {
            e.printStackTrace();
        }try{
            input.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("接受的内容为 "+(new String(b,0,len)));
    }
}
/**
 * 测试类
 * */
class hello{
    public static void main(String[] args) throws IOException {
        Send send=new Send();
        Recive recive=new Recive();
        try{
            //管道连接
            send.getOut().connect(recive.getInput());
        }catch (Exception e) {
            e.printStackTrace();
        }
        new Thread(send).start();
        new Thread(recive).start();
    }
}

【运行结果】:

接受的内容为 hello , Rollen

打印流

/**
 * 使用PrintStream进行输出
 * */
import java.io.*;
 
class hello {
    public static void main(String[] args) throws IOException {
        PrintStream print = new PrintStream(new FileOutputStream(new File("d:"
                + File.separator + "hello.txt")));
        print.println(true);
        print.println("Rollen");
        print.close();
    }
}

【运行结果】:

true

Rollen

【案例2】格式化输出

/**
 * 使用PrintStream进行输出
 * 并进行格式化
 * */
import java.io.*;
class hello {
    public static void main(String[] args) throws IOException {
        PrintStream print = new PrintStream(new FileOutputStream(new File("d:"
                + File.separator + "hello.txt")));
        String name="Rollen";
        int age=20;
        print.printf("姓名:%s. 年龄:%d.",name,age);
        print.close();
    }
}

【运行结果】:

姓名:Rollen. 年龄:20.

【案例3】OutputStream向屏幕上输出内容

/**
 * 使用OutputStream向屏幕上输出内容
 * */
import java.io.*;
class hello {
    public static void main(String[] args) throws IOException {
        OutputStream out=System.out;
        try{
            out.write("hello".getBytes());
        }catch (Exception e) {
            e.printStackTrace();
        }
        try{
            out.close();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}

【运行结果】:

hello

【案例4】输入输出重定向

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
 
/**
 * 为System.out.println()重定向输出
 * */
public class systemDemo{
    public static void main(String[] args){
        // 此刻直接输出到屏幕
        System.out.println("hello");
        File file = new File("d:" + File.separator + "hello.txt");
        try{
            System.setOut(new PrintStream(new FileOutputStream(file)));
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        System.out.println("这些内容在文件中才能看到哦!");//内容在文件中
    }
}

eclipse的控制台输出的是hello

然后当我们查看d盘下面的hello.txt文件的时候,会在里面看到:这些内容在文件中才能看到哦!


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;
 
/**
 * System.err重定向 这个例子也提示我们可以使用这种方法保存错误信息
 * */
public class systemErr{
    public static void main(String[] args){
        File file = new File("d:" + File.separator + "hello.txt");
        System.err.println("这些在控制台输出");
        try{
            System.setErr(new PrintStream(new FileOutputStream(file)));
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        System.err.println("这些在文件中才能看到哦!");
    }
}

【运行结果】:

你会在eclipse的控制台看到红色的输出:“ 这些在控制台输出”,然后在d盘下面的hello.txt中会看到:这些在文件中才能看到哦!

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
 
/**
 * System.in重定向
 * */
public class systemIn{
    public static void main(String[] args){
        File file = new File("d:" + File.separator + "hello.txt");
        if(!file.exists()){
            return;
        }else{
            try{
                System.setIn(new FileInputStream(file));
            }catch(FileNotFoundException e){
                e.printStackTrace();
            }
            byte[] bytes = new byte[1024];
            int len = 0;
            try{
                len = System.in.read(bytes);
            }catch(IOException e){
                e.printStackTrace();
            }
            System.out.println("读入的内容为:" + new String(bytes, 0, len));
        }
    }
}

【运行结果】:

前提是我的d盘下面的hello.txt中的内容是:“ 这些文件中的内容哦!”,然后运行程序,输出的结果为: 读入的内容为:这些文件中的内容哦!

BufferedReader

注意: BufferedReader只能接受字符流的缓冲区,因为每一个中文需要占据两个字节,所以需要将System.in这个字节输入流变为字符输入流,采用:

BufferedReader buf = new BufferedReader(
                new InputStreamReader(System.in));
下面给一个实例
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
 * 使用缓冲区从键盘上读入内容
 * */
public class BufferedReaderDemo{
    public static void main(String[] args){
        BufferedReader buf = new BufferedReader(
                new InputStreamReader(System.in));//System.in这个字节输入流变为字符输入流
        String str = null;
        System.out.println("请输入内容");
        try{
            str = buf.readLine();
        }catch(IOException e){
            e.printStackTrace();
        }
        System.out.println("你输入的内容是:" + str);
    }
}

运行结果:

请输入内容

dasdas

你输入的内容是: dasdas

Scanner

其实我们比较常用的是采用Scanner类来进行数据输入,下面来给一个Scanner的例子吧

import java.util.Scanner;
 
/**
 * Scanner的小例子,从键盘读数据
 * */
public class ScannerDemo{
    public static void main(String[] args){
        Scanner sca = new Scanner(System.in);
        // 读一个整数
        int temp = sca.nextInt();
        System.out.println(temp);
        //读取浮点数
        float flo=sca.nextFloat();
        System.out.println(flo);
        //读取字符
        //...等等的,都是一些太基础的,就不师范了。
    }
}
其实 Scanner 可以接受任何的输入流

【案例2】使用Scanner类从文件中读出内容

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
 
/**
 * Scanner的小例子,从文件中读内容
 * */
public class ScannerDemo{
    public static void main(String[] args){
 
        File file = new File("d:" + File.separator + "hello.txt");
        Scanner sca = null;
        try{
            sca = new Scanner(file);
        }catch(FileNotFoundException e){
            e.printStackTrace();
        }
        String str = sca.next();
        System.out.println("从文件中读取的内容是:" + str);
    }
}

数据操作流DataOutputStreamDataInputStream

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class DataOutputStreamDemo{
    public static void main(String[] args) throws IOException{
        File file = new File("d:" + File.separator + "hello.txt");
        char[] ch = { 'A', 'B', 'C' };
        DataOutputStream out = null;
        out = new DataOutputStream(new FileOutputStream(file));
        for(char temp : ch){
            out.writeChar(temp);
        }
        out.close();
    }
}

【案例2】现在我们在上面例子的基础上,使用DataInputStream读出内容

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
 
public class DataOutputStreamDemo{
    public static void main(String[] args) throws IOException{
        File file = new File("d:" + File.separator + "hello.txt");
        DataInputStream input = new DataInputStream(new FileInputStream(file));
        char[] ch = new char[10];
        int count = 0;
        char temp;
        while((temp = input.readChar()) != 'C'){
            ch[count++] = temp;
        }
        System.out.println(ch);
    }
}

合并流 SequenceInputStream

SequenceInputStream主要用来将2个流合并在一起,比如将两个txt中的内容合并为另外一个txt。下面给出一个实例:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.SequenceInputStream;
 
/**
 * 将两个文本文件合并为另外一个文本文件
 * */
public class SequenceInputStreamDemo{
    public static void main(String[] args) throws IOException{
        File file1 = new File("d:" + File.separator + "hello1.txt");
        File file2 = new File("d:" + File.separator + "hello2.txt");
        File file3 = new File("d:" + File.separator + "hello.txt");
        InputStream input1 = new FileInputStream(file1);
        InputStream input2 = new FileInputStream(file2);
        OutputStream output = new FileOutputStream(file3);
        // 合并流
        SequenceInputStream sis = new SequenceInputStream(input1, input2);
        int temp = 0;
        while((temp = sis.read()) != -1){
            output.write(temp);
        }
        input1.close();
        input2.close();
        output.close();
        sis.close();
    }
}

文件压缩 ZipOutputStream
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
public class ZipOutputStreamDemo1{
    public static void main(String[] args) throws IOException{
        File file = new File("d:" + File.separator + "hello.txt");
        File zipFile = new File("d:" + File.separator + "hello.zip");
        InputStream input = new FileInputStream(file);
        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);
        }
        input.close();
        zipOut.close();
    }
}

【运行结果】

运行结果之前,我创建了一个hello.txt的文件,原本大小56个字节,但是压缩之后产生hello.zip之后,居然变成了175个字节,有点搞不懂。

不过结果肯定是正确的,我只是提出我的一个疑问而已。

【案例2】压缩多个文件

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
 
/**
 * 一次性压缩多个文件
 * */
public class ZipOutputStreamDemo2{
    public static void main(String[] args) throws IOException{
        // 要被压缩的文件夹
        File file = new File("d:" + File.separator + "temp");
        File zipFile = new File("d:" + File.separator + "zipFile.zip");
        InputStream input = null;
        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
                zipFile));
        zipOut.setComment("hello");
        if(file.isDirectory()){
            File[] files = file.listFiles();
            for(int i = 0; i < files.length; ++i){
                input = new FileInputStream(files[i]);
                zipOut.putNextEntry(new ZipEntry(file.getName()
                        + File.separator + files[i].getName()));
                int temp = 0;
                while((temp = input.read()) != -1){
                    zipOut.write(temp);
                }
                input.close();
            }
        }
        zipOut.close();
    }
}






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值