java中的IO整理(3)数据操作流合并流压缩流输入输出重定向 老秋的日志 网易博客

java中的IO整理(3)----数据操作流---合并流--压缩流--输入输出重定向 - 老秋的日志 - 网易博客

java中的IO整理(3)----数据操作流---合并流--压缩流--输入输出重定向 - 老秋的日志 - 网易博客

输入输出重定向

01 import java.io.File;

02 import java.io.FileNotFoundException;

03 import java.io.FileOutputStream;

04 import java.io.PrintStream;

05  

06 /**

07 * 为System.out.println()重定向输出

08 * */

09 public class systemDemo{

10    public static void main(String[] args){

11        // 此刻直接输出到屏幕

12        System.out.println("hello");

13        File file = new File("d:" + File.separator + "hello.txt");

14        try{

15            System.setOut(new PrintStream(new FileOutputStream(file)));

16        }catch(FileNotFoundException e){

17            e.printStackTrace();

18        }

19        System.out.println("这些内容在文件中才能看到哦!");

20    }

21 }

【运行结果】:

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

01 import java.io.File;

02 import java.io.FileNotFoundException;

03 import java.io.FileOutputStream;

04 import java.io.PrintStream;

05  

06 /**

07 * System.err重定向 这个例子也提示我们可以使用这种方法保存错误信息

08 * */

09 public class systemErr{

10    public static void main(String[] args){

11        File file = new File("d:" + File.separator + "hello.txt");

12        System.err.println("这些在控制台输出");

13        try{

14            System.setErr(new PrintStream(new FileOutputStream(file)));

15        }catch(FileNotFoundException e){

16            e.printStackTrace();

17        }

18        System.err.println("这些在文件中才能看到哦!");

19    }

20 }

【运行结果】:

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

01 import java.io.File;

02 import java.io.FileInputStream;

03 import java.io.FileNotFoundException;

04 import java.io.IOException;

05  

06 /**

07 * System.in重定向

08 * */

09 public class systemIn{

10    public static void main(String[] args){

11        File file = new File("d:" + File.separator + "hello.txt");

12        if(!file.exists()){

13            return;

14        }else{

15            try{

16                System.setIn(new FileInputStream(file));

17            }catch(FileNotFoundException e){

18                e.printStackTrace();

19            }

20            byte[] bytes = new byte[1024];

21            int len = ;

22            try{

23                len = System.in.read(bytes);

24            }catch(IOException e){

25                e.printStackTrace();

26            }

27            System.out.println("读入的内容为:" + new String(bytes, , len));

28        }

29    }

30 }

【运行结果】:

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

BufferedReader的小例子

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

BufferedReader buf = new BufferedReader(

                new InputStreamReader(System.in));

下面给一个实例:

01 import java.io.BufferedReader;

02 import java.io.IOException;

03 import java.io.InputStreamReader;

04  

05 /**

06 * 使用缓冲区从键盘上读入内容

07 * */

08 public class BufferedReaderDemo{

09    public static void main(String[] args){

10        BufferedReader buf = new BufferedReader(

11                new InputStreamReader(System.in));

12        String str = null;

13        System.out.println("请输入内容");

14        try{

15            str = buf.readLine();

16        }catch(IOException e){

17            e.printStackTrace();

18        }

19        System.out.println("你输入的内容是:" + str);

20    }

21 }

运行结果:

请输入内容

dasdas

你输入的内容是:dasdas

Scanner类

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

01 import java.util.Scanner;

02  

03 /**

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

05 * */

06 public class ScannerDemo{

07    public static void main(String[] args){

08        Scanner sca = new Scanner(System.in);

09        // 读一个整数

10        int temp = sca.nextInt();

11        System.out.println(temp);

12        //读取浮点数

13        float flo=sca.nextFloat();

14        System.out.println(flo);

15        //读取字符

16        //...等等的,都是一些太基础的,就不师范了。

17    }

18 }

其实Scanner可以接受任何的输入流

下面给一个使用Scanner类从文件中读出内容

01 import java.io.File;

02 import java.io.FileNotFoundException;

03 import java.util.Scanner;

04  

05 /**

06 * Scanner的小例子,从文件中读内容

07 * */

08 public class ScannerDemo{

09    public static void main(String[] args){

10  

11        File file = new File("d:" + File.separator + "hello.txt");

12        Scanner sca = null;

13        try{

14            sca = new Scanner(file);

15        }catch(FileNotFoundException e){

16            e.printStackTrace();

17        }

18        String str = sca.next();

19        System.out.println("从文件中读取的内容是:" + str);

20    }

21 }

【运行结果】:

从文件中读取的内容是:这些文件中的内容哦!

数据操作流DataOutputStream、DataInputStream类

01 import java.io.DataOutputStream;

02 import java.io.File;

03 import java.io.FileOutputStream;

04 import java.io.IOException;

05  

06 public class DataOutputStreamDemo{

07    public static void main(String[] args) throws IOException{

08        File file = new File("d:" + File.separator + "hello.txt");

09        char[] ch = { 'A', 'B', 'C' };

10        DataOutputStream out = null;

11        out = new DataOutputStream(new FileOutputStream(file));

12        for(char temp : ch){

13            out.writeChar(temp);

14        }

15        out.close();

16    }

17 }

A B C

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

01 import java.io.DataInputStream;

02 import java.io.File;

03 import java.io.FileInputStream;

04 import java.io.IOException;

05  

06 public class DataOutputStreamDemo{

07    public static void main(String[] args) throws IOException{

08        File file = new File("d:" + File.separator + "hello.txt");

09        DataInputStream input = new DataInputStream(new FileInputStream(file));

10        char[] ch = new char[10];

11        int count = ;

12        char temp;

13        while((temp = input.readChar()) != 'C'){

14            ch[count++] = temp;

15        }

16        System.out.println(ch);

17    }

18 }

【运行结果】:

AB

合并流 SequenceInputStream

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

01 import java.io.File;

02 import java.io.FileInputStream;

03 import java.io.FileOutputStream;

04 import java.io.IOException;

05 import java.io.InputStream;

06 import java.io.OutputStream;

07 import java.io.SequenceInputStream;

08  

09 /**

10 * 将两个文本文件合并为另外一个文本文件

11 * */

12 public class SequenceInputStreamDemo{

13    public static void main(String[] args) throws IOException{

14        File file1 = new File("d:" + File.separator + "hello1.txt");

15        File file2 = new File("d:" + File.separator + "hello2.txt");

16        File file3 = new File("d:" + File.separator + "hello.txt");

17        InputStream input1 = new FileInputStream(file1);

18        InputStream input2 = new FileInputStream(file2);

19        OutputStream output = new FileOutputStream(file3);

20        // 合并流

21        SequenceInputStream sis = new SequenceInputStream(input1, input2);

22        int temp = ;

23        while((temp = sis.read()) != -1){

24            output.write(temp);

25        }

26        input1.close();

27        input2.close();

28        output.close();

29        sis.close();

30    }

31 }

【运行结果】

结果会在hello.txt文件中包含hello1.txt和hello2.txt文件中的内容。

文件压缩 ZipOutputStream类

先举一个压缩单个文件的例子吧:

01 import java.io.File;

02 import java.io.FileInputStream;

03 import java.io.FileOutputStream;

04 import java.io.IOException;

05 import java.io.InputStream;

06 import java.util.zip.ZipEntry;

07 import java.util.zip.ZipOutputStream;

08  

09 public class ZipOutputStreamDemo1{

10    public static void main(String[] args) throws IOException{

11        File file = new File("d:" + File.separator + "hello.txt");

12        File zipFile = new File("d:" + File.separator + "hello.zip");

13        InputStream input = new FileInputStream(file);

14        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(

15                zipFile));

16        zipOut.putNextEntry(new ZipEntry(file.getName()));

17        // 设置注释

18        zipOut.setComment("hello");

19        int temp = ;

20        while((temp = input.read()) != -1){

21            zipOut.write(temp);

22        }

23        input.close();

24        zipOut.close();

25    }

26 }

【运行结果】

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

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

上面的这个例子测试的是压缩单个文件,下面的们来看看如何压缩多个文件。

01 import java.io.File;

02 import java.io.FileInputStream;

03 import java.io.FileOutputStream;

04 import java.io.IOException;

05 import java.io.InputStream;

06 import java.util.zip.ZipEntry;

07 import java.util.zip.ZipOutputStream;

08  

09 /**

10 * 一次性压缩多个文件

11 * */

12 public class ZipOutputStreamDemo2{

13    public static void main(String[] args) throws IOException{

14        // 要被压缩的文件夹

15        File file = new File("d:" + File.separator + "temp");

16        File zipFile = new File("d:" + File.separator + "zipFile.zip");

17        InputStream input = null;

18        ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(

19                zipFile));

20        zipOut.setComment("hello");

21        if(file.isDirectory()){

22            File[] files = file.listFiles();

23            for(int i = ; i < files.length; ++i){

24                input = new FileInputStream(files[i]);

25                zipOut.putNextEntry(new ZipEntry(file.getName()

26                        + File.separator + files[i].getName()));

27                int temp = ;

28                while((temp = input.read()) != -1){

29                    zipOut.write(temp);

30                }

31                input.close();

32            }

33        }

34        zipOut.close();

35    }

36 }

【运行结果】

先看看要被压缩的文件吧:

接下来看看压缩之后的:

大家自然想到,既然能压缩,自然能解压缩,在谈解压缩之前,我们会用到一个ZipFile类,先给一个这个例子吧。java中的每一个压缩文件都是可以使用ZipFile来进行表示的

01 import java.io.File;

02 import java.io.IOException;

03 import java.util.zip.ZipFile;

04  

05 /**

06 * ZipFile演示

07 * */

08 public class ZipFileDemo{

09    public static void main(String[] args) throws IOException{

10        File file = new File("d:" + File.separator + "hello.zip");

11        ZipFile zipFile = new ZipFile(file);

12        System.out.println("压缩文件的名称为:" + zipFile.getName());

13    }

14 }

【运行结果】:

压缩文件的名称为:d:\hello.zip

现在我们呢是时候来看看如何加压缩文件了,和之前一样,先让我们来解压单个压缩文件(也就是压缩文件中只有一个文件的情况),我们采用前面的例子产生的压缩文件hello.zip

01 import java.io.File;

02 import java.io.FileOutputStream;

03 import java.io.IOException;

04 import java.io.InputStream;

05 import java.io.OutputStream;

06 import java.util.zip.ZipEntry;

07 import java.util.zip.ZipFile;

08  

09 /**

10 * 解压缩文件(压缩文件中只有一个文件的情况)

11 * */

12 public class ZipFileDemo2{

13    public static void main(String[] args) throws IOException{

14        File file = new File("d:" + File.separator + "hello.zip");

15        File outFile = new File("d:" + File.separator + "unZipFile.txt");

16        ZipFile zipFile = new ZipFile(file);

17        ZipEntry entry = zipFile.getEntry("hello.txt");

18        InputStream input = zipFile.getInputStream(entry);

19        OutputStream output = new FileOutputStream(outFile);

20        int temp = ;

21        while((temp = input.read()) != -1){

22            output.write(temp);

23        }

24        input.close();

25        output.close();

26    }

27 }

【运行结果】:

解压缩之前:

这个压缩文件还是175字节

解压之后产生:

又回到了56字节,表示郁闷。

现在让我们来解压一个压缩文件中包含多个文件的情况吧

ZipInputStream类

当我们需要解压缩多个文件的时候,ZipEntry就无法使用了,如果想操作更加复杂的压缩文件,我们就必须使用ZipInputStream类

01 import java.io.File;

02 import java.io.FileInputStream;

03 import java.io.FileOutputStream;

04 import java.io.IOException;

05 import java.io.InputStream;

06 import java.io.OutputStream;

07 import java.util.zip.ZipEntry;

08 import java.util.zip.ZipFile;

09 import java.util.zip.ZipInputStream;

10  

11 /**

12 * 解压缩一个压缩文件中包含多个文件的情况

13 * */

14 public class ZipFileDemo3{

15    public static void main(String[] args) throws IOException{

16        File file = new File("d:" + File.separator + "zipFile.zip");

17        File outFile = null;

18        ZipFile zipFile = new ZipFile(file);

19        ZipInputStream zipInput = new ZipInputStream(new FileInputStream(file));

20        ZipEntry entry = null;

21        InputStream input = null;

22        OutputStream output = null;

23        while((entry = zipInput.getNextEntry()) != null){

24            System.out.println("解压缩" + entry.getName() + "文件");

25            outFile = new File("d:" + File.separator + entry.getName());

26            if(!outFile.getParentFile().exists()){

27                outFile.getParentFile().mkdir();

28            }

29            if(!outFile.exists()){

30                outFile.createNewFile();

31            }

32            input = zipFile.getInputStream(entry);

33            output = new FileOutputStream(outFile);

34            int temp = ;

35            while((temp = input.read()) != -1){

36                output.write(temp);

37            }

38            input.close();

39            output.close();

40        }

41    }

42 }

【运行结果】:

被解压的文件:

解压之后再D盘下会出现一个temp文件夹,里面内容:

PushBackInputStream回退流

01 import java.io.ByteArrayInputStream;

02 import java.io.IOException;

03 import java.io.PushbackInputStream;

04  

05 /**

06 * 回退流操作

07 * */

08 public class PushBackInputStreamDemo{

09    public static void main(String[] args) throws IOException{

10        String str = "hello,rollenholt";

11        PushbackInputStream push = null;

12        ByteArrayInputStream bat = null;

13        bat = new ByteArrayInputStream(str.getBytes());

14        push = new PushbackInputStream(bat);

15        int temp = ;

16        while((temp = push.read()) != -1){

17            if(temp == ','){

18                push.unread(temp);

19                temp = push.read();

20                System.out.print("(回退" + (char) temp + ") ");

21            }else{

22                System.out.print((char) temp);

23            }

24        }

25    }

26 }

【运行结果】:

hello(回退,) rollenholt

1 /**

2 * 取得本地的默认编码

3 * */

4 public class CharSetDemo{

5    public static void main(String[] args){

6        System.out.println("系统默认编码为:" + System.getProperty("file.encoding"));

7    }

8 }

【运行结果】:

系统默认编码为:GBK

乱码的产生:

import java.io.File;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.OutputStream;

/**

 * 乱码的产生

 * */

public class CharSetDemo2{

    public static void main(String[] args) throws IOException{

        File file = new File("d:" + File.separator + "hello.txt");

        OutputStream out = new FileOutputStream(file);

        byte[] bytes = "你好".getBytes("ISO8859-1");

        out.write(bytes);

        out.close();

    }

}

【运行结果】:

??

 一般情况下产生乱码,都是由于编码不一致的问题。

原文地址:https://www.cnblogs.com/lexus/p/2370402.html