欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

I/O复习(一)——Java I/O

程序员文章站 2022-06-14 14:38:56
...

I/O复习(一)——Java I/O

File

特定文件

FileDemo.java:

import java.io.File;

public class FileDemo {
    static void p(String s) {
        System.out.println(s);
    }

    public static void main(String[] args) {
        File f1 = new File("./src/main/java/com/yangyun/javae/chapter20/FileDemo.java");
        // 文件名
        p("File Name:" + f1.getName());
        // 文件路径
        p("Path:" + f1.getPath());
        // 绝对路径
        p("Abs Path:" + f1.getAbsolutePath());
        // 父级
        p("Parent:" + f1.getParent());
        // 文件是否存在
        p(f1.exists() ? "exists" : "does not exist");
        // 文件是否可写
        p(f1.canWrite() ? "is writeable" : "is not writeable");
        // 文件是否可读
        p(f1.canRead() ? "is readable" : "is not readable");
        // 是文件还是文件夹
        p("is " + (f1.isDirectory() ? " a directory" : "not a directory"));
        // 是否是常规文件,设备驱动和命名管道返回false
        p(f1.isFile() ? "is normal file" : "might be a named pipe");
        // 文件是否具有绝对路径
        p(f1.isAbsolute() ? "is absolute" : "is not absolute");
        // 文件上次修改时间
        p("File last modified:" + f1.lastModified());
        // 文件大小
        p("File size:" + f1.length() + " Bytes");
    }
}

一个目录下的一组文件的名称

DirList.java:

import java.io.File;
import java.io.FilenameFilter;
import java.util.Arrays;
import java.util.regex.Pattern;


public class DirList {
    /**
     * 传向filter()的参数必须是final的。这在匿名内部类中是必须的,这样才能使用来自该类范围之外的对象。
     * @param regex
     * @return
     */
    public static FilenameFilter filter(final String regex) {
        // 创建匿名内部类
        return new FilenameFilter() {
            private Pattern pattern = Pattern.compile(regex);
            @Override
            public boolean accept(File dir, String name) {
                return pattern.matcher(name).matches();
            }
        };
    }

    public static void main(String[] args) {
        // 获取当前项目下的文件名称
        File path = new File(".");
        String[] list;
        if (args.length == 0) {
            list = path.list();
        } else {
            list = path.list(filter(args[0]));
        }

        // 对结果进行排序
        Arrays.sort(list, String.CASE_INSENSITIVE_ORDER);

        for (String dirItem : list) {
            System.out.println(dirItem);
        }
    }
}

DirListOnly.java:

import java.io.File;
import java.io.FilenameFilter;

class OnlyExt implements FilenameFilter {
    String ext;

    public OnlyExt(String ext) {
        this.ext = "." + ext;
    }

    @Override
    public boolean accept(File dir, String name) {
        return name.endsWith(ext);
    }
}

public class DirListOnly {
    public static void main(String[] args) {
        String dirname = "/Users/yangyun/Documents/personal_project/thinking-in-java/src/main/java/com/yangyun/javaee/chapte1";
        File f1 = new File(dirname);
        FilenameFilter only = new OnlyExt("java");
        String[] s = f1.list(only);
        for (int i = 0; i < s.length; i++) {
            System.out.println(s[i]);
        }
       
    }
}

创建目录

MakeDirDemo.java:

import java.io.File;

public class MakeDirDemo {
    public static void main(String[] args) {
        String dirname = "/Users/yangyun/Documents/personal_project/thinking-in-java/src/main/java/com/yangyun/javae/chapter40";
        File f1 = new File(dirname);
        if (f1.mkdir()) {
            System.out.println("mkdir success");
        } else {
            System.out.println("mkdir fail");
        }

    }
}

MakeDirsDemo.java:

import java.io.File;

public class MakeDirsDemo {
    public static void main(String[] args) {
        String dirname = "/Users/yangyun/Documents/personal_project/thinking-in-java/src/main/java/com/yangyun/javae/yy/chapter40";
        File f1 = new File(dirname);
        if (f1.mkdirs()) {
            System.out.println("mkdirs success");
        } else {
            System.out.println("mkdirs fail");
        }

    }
}

字节流

InputStream(输入流)

表1-1 InputStream类型
功能 构造器/如何使用
ByteArrayInputStream 允许将内存的缓冲区当作InputStream使用 缓冲区,字节将从中取出
作为一种数据源:将其与FilterInputStream
对象相连使用以提供有用的接口
FileInputStream 用于从文件中读取信息 字符串,表示文件名、文件或FileDescriptor对象作为一种数据源:将其与FilterInputStream对象相连以提供有用的接口
SequenceInputStream 将两个或多个InputStream
对象转换成单一InputStream
两个InputStream对象或一个容纳InputStream对象的容器Enumeration
作为一种数据源:将其与FilterInputStream对象相连以提供有用的接口
PipedInputStream 产生用于写入相关PipedOutputStream
的数据。实现“管道化”概念
PipedOutputStream作为多线程中数据源:将其与FilterInputStream对象相连以提供有用的接口
FilterInputStream 抽象类,作为装饰器的接口,其中,装饰器为其他的InputStream类提供有用的功能 见表1-3

ByteArrayInputStrea

ByteArrayInputStreamDemo.java:

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamDemo {
    public static void main(String[] args) {
        String tmp = "abcdefghijklmnopqrstuvwzyz";
        byte[] b = tmp.getBytes();

        ByteArrayInputStream input1 = new ByteArrayInputStream(b);
        ByteArrayInputStream input2 = new ByteArrayInputStream(b, 0, 3);
    }
}

ByteArrayInputStreamReset.java:

import java.io.ByteArrayInputStream;

public class ByteArrayInputStreamReset {
    public static void main(String[] args) {
        String tmp = "abcdefg";
        byte[] b = tmp.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(b);

        for (int i = 0; i < 2; i++) {
            int c;

            while ((c = in.read()) != -1) {
                if (i == 0) {
                    char val = (char) c;
                    System.out.print(val);
                    if (val == 'a') {
                        // 设置流中当前标记的位置
                        in.mark(1);
                    }
                } else {
                    System.out.print(Character.toUpperCase((char) c));
                }
            }
            System.out.println();
            // 如果没有调用mark( )方法,reset( )方法会将指针设置为流的开头,否则回到上次mark( )的地方
            in.reset();
        }
    }
}

FileInputStream

FileInputStreamDemo.java:

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileInputStreamDemo {
    public static void main(String[] args) {
        int size;
        try (FileInputStream f = new FileInputStream("./src/main/java/com/yangyun/javae/chapter20/FileInputStreamDemo.java")) {
            System.out.println("Total Available Bytes:" + (size = f.available()));
            int n = size / 40;
            System.out.println("First " + n + " bytes of the file one read() at a time");
            for (int i = 0; i < n; i++) {
                System.out.print((char) f.read());
            }
            System.out.println("\nStill Available:" + f.available());
            System.out.println("------------------------------------");


            System.out.println("Reading the next " + n + " with one read(b[])");
            byte[] b = new byte[n];
            if (f.read(b) != n) {
                System.err.println("couldn't read " + n + " bytes.");
            }
            System.out.println(new String(b, 0, n));
            System.out.println("\nStill Available:" + (size = f.available()));
            System.out.println("Skipping half of remaining bytes with skip()");
            f.skip(size / 2);
            System.out.println("Still Available:" + f.available());
            System.out.println("------------------------------------");


            System.out.println("Reading " + n / 2 + " into the end of array");
            // 返回成功读取的字节数
            if (f.read(b, n / 2, n / 2) != n / 2) {
                System.out.println("couldn't read " + n / 2 + " bytes.");
            }
            System.out.println(new String(b, 0, b.length));
            System.out.println("\nStill Available:" + f.available());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

BufferedInputStream

BufferInputStreamDemo.java:

import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.IOException;

public class BufferedInputStreamDemo {
    public static void main(String[] args) {
        String s = "This is a &copy; copyright symbol but this is &copy not.\n";
        byte[] buf = s.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(buf);

        int c;
        boolean marked = false;

        try (BufferedInputStream f = new BufferedInputStream(in)) {
            while ((c = f.read()) != -1) {
                switch (c) {
                    case '&':
                        if (!marked) {
                            f.mark(32);
                            marked = true;
                        } else {
                            marked = false;
                        }
                        break;
                    case ';':
                        if (marked) {
                            marked = false;
                            System.out.print("(c)");
                        } else {
                            System.out.print((char) c);
                        }
                        break;
                    case ' ':
                        if (marked) {
                            marked = false;
                            f.reset();
                            System.out.print("&");
                        } else {
                            System.out.print((char) c);
                        }
                        break;
                    default:
                        if (!marked) {
                            System.out.print((char) c);
                        }
                        break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

SequenceInputStream

SequenceInputStreamDemo.java:

import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Enumeration;
import java.util.Vector;

class InputStreamEnumerator implements Enumeration<FileInputStream> {

    private Enumeration<String> files;

    public InputStreamEnumerator(Vector<String> files) {
        this.files = files.elements();
    }

    @Override
    public boolean hasMoreElements() {
        return files.hasMoreElements();
    }

    @Override
    public FileInputStream nextElement() {
        try {
            return new FileInputStream(files.nextElement().toString());
        } catch (FileNotFoundException e) {
            return null;
        }
    }
}

public class SequenceInputStreamDemo {
    public static void main(String[] args) {
        int c;
        Vector<String> files = new Vector<>();
        files.addElement("file1.txt");
        files.addElement("file2.txt");
        files.addElement("file3.txt");
        InputStreamEnumerator ise = new InputStreamEnumerator(files);


        try (InputStream input = new SequenceInputStream(ise)) {
            while ((c = input.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

OutputStream(输出流)

表1-2 OutputStream类型
功能 构造器/如何使用
ByteArrayOutputStream 在内存中创建缓冲区。所有送往流的数据都要放置在此缓冲区 缓冲区初始化尺寸(可选的)用于指定数据的目的地:将其与FilterOutputStream对象相连以提供有用的接口
FileOutputStream 用于将信息写至文件 字符串,表示文件名、文件或FileDescriptor对象。指定数据的目的地:将其与FilterOutputStream对象相连以提供有用的接口
PipedOutputStream 任何写入其中的信息都会自动作为相关
PipedOutputStream的输出。实现管道化概念。
PipedInputStream指定用于多线程的数据的目的地:将其与FilterOutputStream对象相连以提供有用的接口
FilterOutputStream 抽象类,作为装饰器的接口。其中,装饰器为其他OutputStream提供有用功能 见表1-4

ByteArrayOutputStream

ByteArrayOutputStreamDemo.java:

import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class ByteArrayOutputStreamDemo {
    public static void main(String[] args) {
        ByteArrayOutputStream f = new ByteArrayOutputStream();
        String s = "This should end up in the array";
        byte[] buf = s.getBytes();

        try {
            f.write(buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Buffer as a String");
        System.out.println(f.toString());
        System.out.println("Into array");
        byte[] b = f.toByteArray();
        for (int i = 0; i < b.length; i++) {
            System.out.print((char) b[i]);
        }
        System.out.println("\nTo an OutputStream()");

        try (FileOutputStream f2 = new FileOutputStream("test.txt")) {
            // 将f的内容写入test.txt文件中
            f.writeTo(f2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Doing a reset");
        f.reset();
        for (int i = 0; i < 3; i++) {
            f.write('X');
        }
        System.out.println(f.toString());
    }
}

FileOutputStream

FileOutputStreamDemo.java:

import java.io.FileOutputStream;
import java.io.IOException;

public class FileOutputStreamDemo {
    public static void main(String[] args) {
        String source = "Now is the time for all good men\n"
                + " to come to the aid of their country\n"
                + " and pay their due taxes.";

        byte[] buf = source.getBytes();

        try ( FileOutputStream f0 = new FileOutputStream("file1.txt");
              FileOutputStream f1 = new FileOutputStream("file2.txt");
              FileOutputStream f2 = new FileOutputStream("file3.txt")){

            // 写第一个文件
            for (int i = 0; i < buf.length; i += 2) {
                f0.write(buf[i]);
            }

            // 写第二个文件
            f1.write(buf);

            // 写第三个文件
            f2.write(buf, buf.length - buf.length / 4, buf.length / 4);
        } catch(IOException e){
            System.out.println("An I/O Error Occurred");
        }
    }
}

FilterInputStream

表1-3 FilterInputStream类型
功能 构造器/如何使用
DataInputStream 与DataOutputStream搭配使用,因此我们
可以按照移植方式从流读取基本数据类型
InputStream包含用于读取基本类型数据的全部接口
BufferedInputStream 使用它可以防止每次读取时都进行实际写操作。代表“使用缓冲区” InputStream,可以指定缓冲区大小;本质上不提供接口,只不过是向进程中添加缓冲区所必需的。与接口对象搭配
LineNumberInputStream 跟踪输入流中的行号;可调用getLineNumber()和setLineNumber(int) IntputStream仅增加了行号,因此可能要与接口对象搭配使用
PushbackInputStream 具有“能弹出一个字节的缓冲区”。因此可以将读到的最后一个字符回退 InputStream通常作为编译器的扫描器,之所以包含在内是因为Java编译器的需要,我们可能永远不会用到

DataInputStream

DataIODemo.java:

import java.io.*;

public class DataIODemo {
    public static void main(String[] args) {
        // 写数据
        try (DataOutputStream dout = new DataOutputStream(new FileOutputStream("Test.txt"))) {
            dout.writeDouble(98.6);
            dout.writeInt(1000);
            dout.writeBoolean(true);

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (DataInputStream din = new DataInputStream(new FileInputStream("Test.txt"))) {
            double d = din.readDouble();
            int i = din.readInt();
            boolean b = din.readBoolean();
            System.out.println("Here are the values:" + d + " " + i + " " + b);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PushbackInputStream

PushInputStreamDemo.java:

import java.io.ByteArrayInputStream;
import java.io.PushbackInputStream;

public class PushInputStreamDemo {
    public static void main(String args[]) throws Exception {
        // 定义字符串
        String str = "www.baidu.com";
        // 定义回退流对象
        PushbackInputStream push = null;
        // 定义内存输入流
        ByteArrayInputStream bai = null;
        // 实例化内存输入流
        bai = new ByteArrayInputStream(str.getBytes());
        // 从内存中读取数据
        push = new PushbackInputStream(bai);
        System.out.print("读取之后的数据为:");
        int temp = 0;
        // 读取内容
        while ((temp = push.read()) != -1) {
            // 判断是否读取到了“.”
            if (temp == '.') {
                // 放回到缓冲区之中
                push.unread(temp);
                // 再读一遍
                temp = push.read();
                System.out.print("(退回" + (char) temp + ")");
            } else {
                // 输出内容
                System.out.print((char) temp);
            }
        }
    }
}

PushbackInputStreamDemo.java:

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.PushbackInputStream;

public class PushbackInputStreamDemo {
    public static void main(String[] args) {
        String s = "if (a == 4) a = 0;\n";
        byte[] buf = s.getBytes();
        ByteArrayInputStream in = new ByteArrayInputStream(buf);
        int c;
        try (PushbackInputStream f = new PushbackInputStream(in)) {
            while ((c = f.read()) != -1) {
                switch (c) {
                    case '=':
                        if ((c = f.read()) == '=') {
                            System.out.print(".eq.");
                        } else {
                            System.out.print("<-");
                            f.unread(c);
                        }
                        break;
                    default:
                        System.out.print((char) c);
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

注意事项:PushbackInputStream对象会使得InputStream对象的mark( )或reset( )方法无效。所以对于准备使用mark( )或reset( )方法的任何流来说,都应该先使用markSupport( )方法进行检查。

FilterOutputStream

表1-4 FilterOutputStream类型
功能 构造器/如何使用
DataOutputStream 与DataInputStream搭配使用,因此可以
按照可移植方式向流中写入基本类型数据
OutputStream包含用于读取基本类型数据的全部接口
PrintStream 用于产生格式化输出。其中DataOutputStream处理数据的存储,PrintStream处理显示 OutputStream,可以用boolean值指示是否在每次换行时清空缓冲区(可选的)应该是对OutputStream对象的“final”封装。可能会经常使用到它
BufferedOutputStream 使用它以避免每次发送数据时都要进行实际的鞋操作。代表“使用缓冲区”。可以调用flush()清空缓冲区 OutputStream,可以指定缓冲区大小(可选的)

DataOutputStream

DataIODemo:

RandomAccessFile

UsingRandomAccessFile.java:

import java.io.IOException;
import java.io.RandomAccessFile;

public class UsingRandomAccessFile {
    static String file = "/Users/yangyun/Documents/linux/shell/exam1/test1";

    static void display() throws IOException {
        RandomAccessFile rf = new RandomAccessFile(file, "r");
        for (int i = 0; i < 7; i++) {
            System.out.println("Value " + i + ":" + rf.readDouble());
        }

        System.out.println(rf.readUTF());
        rf.close();
    }

    public static void main(String[] args) throws IOException {
        RandomAccessFile rf = new RandomAccessFile(file, "rw");
        for (int i = 0; i < 7; i++) {
            rf.writeDouble(i * 1.414);
        }
        rf.writeUTF("The end of the file");
        rf.close();
        display();
        rf = new RandomAccessFile(file, "rw");
        rf.seek(5 * 8);
        rf.writeDouble(47.0001);
        rf.close();
        display();
    }
}

字符流

InputStream和OutputStream在以面向字节形式的I/O中仍可以提供极有价值的功能,Reader和Writer则提供兼容Unicode与面向字符的I/O功能。
一般我们把来自于“字节”层次结构中的类和“字符”层次结构中的类结合起来使用。为了实现这个目的,要用到“适配器”(adapter)类:InputStreamReader可以把InputStream转换为Reader,而OutputStreamWriter可以把OutputStream转换为Writer。设计Reader和Writer继承层次结构主要是为了国际化。老的I/O流继承层次结构仅支持8位字节流,并且不能很好地处理16位的Unicode字符。由于Unicode用于字符国际化,所以添加Reader和Writer继承层次结构就是为了在所有的I/O操作中都支持Unicode。

Reader

FileReader

FileReaderDemo.java:

mport java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

public class FileReaderDemo {
    public static void main(String[] args) {
        try (FileReader fr = new FileReader("/Users/yangyun/Documents/personal_project/thinking-in-java/src/main/java/com/yangyun/javae/chapter20/FileReaderDemo.java")) {
            int c;
            while ((c = fr.read()) != -1) {
                System.out.print((char) c);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CharArrayReader

CharArrayReaderDemo.java:

import java.io.CharArrayReader;
import java.io.IOException;

public class CharArrayReaderDemo {
    public static void main(String[] args) {
        String tmp = "abcdefghijklmnopqrstuvwxyz";
        int length = tmp.length();
        char[] c = new char[length];

        tmp.getChars(0, length, c, 0);

        int i;

        try (CharArrayReader input1 = new CharArrayReader(c)) {
            System.out.println("input1 is:");
            while ((i = input1.read()) != -1) {
                System.out.print((char) i);
            }
            System.out.println();
        } catch (IOException e) {
            System.out.println("I/O Error:" + e);
        }

        try (CharArrayReader input2 = new CharArrayReader(c,0,5)) {
            System.out.println("input2 is:");
            while ((i = input2.read()) != -1) {
                System.out.print((char) i);
            }
            System.out.println();
        } catch (IOException e) {
            System.out.println("I/O Error:" + e);
        }
    }
}

BufferedReader

BufferedReaderDemo.java:

import java.io.*;

public class BufferedReaderDemo {
    public static void main(String[] args) {
        String s = "This is a &copy; copyright symbol but this is &copy not.\n";
        char[] buf = new char[s.length()];
        s.getChars(0, s.length(), buf, 0);

        CharArrayReader in = new CharArrayReader(buf);
        int c;
        boolean marked = false;

        try (BufferedReader f = new BufferedReader(in)) {
            while ((c = f.read()) != -1) {
                switch (c) {
                    case '&':
                        if (!marked) {
                            f.mark(32);
                            marked = true;
                        } else {
                            marked = false;
                        }
                        break;
                    case ';':
                        if (marked) {
                            marked = false;
                            System.out.print("(c)");
                        } else {
                            System.out.print((char) c);
                        }
                        break;
                    case ' ':
                        if (marked) {
                            marked = false;
                            f.reset();
                            System.out.print("&");
                        } else {
                            System.out.print((char) c);
                        }
                        break;
                    default:
                        if (!marked) {
                            System.out.print((char) c);
                        }
                        break;
                }
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

PushbackReader

PushbackReaderDemo.java:

import java.io.*;

public class PushbackReaderDemo {
    public static void main(String[] args) {
        String s = "if (a == 4) a = 0;\n";
        char[] buf = new char[s.length()];
        s.getChars(0,s.length(),buf,0);
        CharArrayReader in = new CharArrayReader(buf);
        int c;
        try (PushbackReader f = new PushbackReader(in)) {
            while ((c = f.read()) != -1) {
                switch (c) {
                    case '=':
                        if ((c = f.read()) == '=') {
                            System.out.print(".eq.");
                        } else {
                            System.out.print("<-");
                            f.unread(c);
                        }
                        break;
                    default:
                        System.out.print((char) c);
                        break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Writer

FileWriter

FileWriterDemo.java:

import java.io.FileWriter;
import java.io.IOException;

public class FileWriterDemo {
    public static void main(String[] args) {
        String source = "Now is the time for all good men\n"
                + " to come to the aid of their country\n"
                + " and pay their due taxes.";

        char[] buffer = new char[source.length()];

        source.getChars(0, source.length(), buffer, 0);


        try (FileWriter f0 = new FileWriter("file1.txt");
             FileWriter f1 = new FileWriter("file2.txt");
             FileWriter f2 = new FileWriter("file3.txt")) {
            for (int i = 0; i < buffer.length; i += 2) {
                f0.write(buffer[i]);
            }

            f1.write(buffer);

            f2.write(buffer, buffer.length - buffer.length / 4, buffer.length / 4);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

CharArrayWriter

CharArrayWriterDemo.java:

import java.io.CharArrayWriter;
import java.io.FileWriter;
import java.io.IOException;

public class CharArrayWriterDemo {
    public static void main(String[] args) {
        CharArrayWriter f = new CharArrayWriter();
        String s = "This should end up in the array";
    
        char[] buf = new char[s.length()];

        s.getChars(0, s.length(), buf, 0);
        try {
            f.write(buf);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Buffer as a String");
        System.out.println(f.toString());
        System.out.println("Into array");

        char[] c = f.toCharArray();
        for (int i = 0; i < c.length; i++) {
            System.out.print(c[i]);
        }

        System.out.println("\nTo a FileWriter()");

        try (FileWriter f2 = new FileWriter("test.txt")) {
            f.writeTo(f2);
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Doing a reset");
        f.reset();

        for (int i = 0; i < 3; i++) {
            f.write('X');
        }
        System.out.println(f.toString());
    }
}

PrintWriter

BasicFileOutput.java:

import java.io.*;

public class BasicFileOutput {
    static String file = "BasicFileOutput.out";

    public static String read(String filename) throws IOException {
        // 按行读取
        BufferedReader in = new BufferedReader(new FileReader(filename));
        String s;
        StringBuilder sb = new StringBuilder();
        while ((s = in.readLine()) != null) {
            sb.append(s + "\n");
        }
        // 关闭流
        in.close();
        return sb.toString();
    }


    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new StringReader(BufferedInputFile.read(
                "/Users/yangyun/Documents/linux/shell/exam1/test3")));
        PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file)));
        int lineCount = 1;
        String s;
        while ((s = in.readLine()) != null) {
            out.println(lineCount++ + ":" + s);
        }
        out.close();

        // 展示保存的文件
        System.out.println(BufferedInputFile.read(file));
    }
}

ChangeSystemOut.java:

import java.io.PrintWriter;
// PrintWriter有一个可以接受OutputStream作为参数的构造器
public class ChangeSystemOut {
    public static void main(String[] args) {
        PrintWriter out = new PrintWriter(System.out, true);
        out.println("Hello,world");
    }
}

标准I/O重定向

Redirecting.java:

import java.io.*;

public class Redirecting {
    public static void main(String[] args) throws IOException {
        PrintStream console = System.out;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream("/Users/yangyun/Documents/linux/shell/exam1/test2"));
        PrintStream out = new PrintStream(new BufferedOutputStream(new FileOutputStream("test.out")));
        System.setIn(in);
        System.setOut(out);
        System.setErr(out);
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String s;
        while ((s = br.readLine()) != null) {
            System.out.println(s);
        }
        System.out.println("hello");
        out.close();

        System.setOut(console);
        System.out.println("hello");
    }
}

串行化

SerializationDemo.java:

import java.io.*;

class MyClass implements Serializable {
    //transient String s;
    String s;
    private int i;
    private double d;

    public MyClass(String s, int i, double d) {
        this.s = s;
        this.i = i;
        this.d = d;
    }

    @Override
    public String toString() {
        return "s=" + s + ";i=" + i + ";d=" + d;
    }
}
public class SerializationDemo {
    public static void main(String[] args) throws IOException {
        try (ObjectOutputStream objOStrm = new ObjectOutputStream(new FileOutputStream("serial"))) {
            MyClass object1 = new MyClass("Hello", -7, 2.7e10);

            System.out.println("object1:" + object1);

            objOStrm.writeObject(object1);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try (ObjectInputStream objIStrm = new ObjectInputStream(new FileInputStream("serial"))) {
            MyClass object2 = (MyClass) objIStrm.readObject();
            System.out.println("object2:" + object2);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
       
    }
}

字节流与字符流的对应关系

表1-5 字节流与字符流的对应关系
字节流 字符流
InputStream Reader(适配器:InputStreamReader)
OutputStream Writer(适配器:OutputStreamWriter)
FileInputStream FileReader
FileOutputStream FileWriter
StringBufferInputStream(Deprecated) StringReader
StringWriter
ByteArrayInputStream CharArrayReader
ByteArrayOutputStream CharArrayWriter
PipedInputStream PipedReader
PipedOutputStream PipedWriter
FilterInputStream FilterReader
FilterOutputStream FilterWriter
BufferedInputStream BufferedReader
BufferedOutputStream
PrintStream PrintWriter
LineNumberInputStream(Deprecated) LineNumberReader
StreamTokenizer StreamTokenizer(使用接受Reader的构造器)
PushbackInputStream PushbackReader