Getting Started with Java classes and the File IO streams

1.File class

java.io.File class is an abstract file and directory path names indicate, mainly used to create files and directories, find and delete files.

Construction method:

  • File public (String pathname) : by the given pathname string to create a new abstract pathname conversion File instance.
  • File public (String parent, String Child) : from a parent pathname string and a child pathname string to create a new File instance.
  • File public (File parent, String Child) : from a parent abstract pathname and a child pathname string to create a new File instance.

Common methods:

    • String getAbsolutePath public () : Returns File absolute pathname string.
    • String getPath public () : this File convert pathname string.
    • String getName public () : Returns the result File name of the file or directory indicated.
    • Long length public () : returns the result File length of the file representation.
    • boolean EXISTS public () : This File file or directory indicated actually exists.
    • boolean isDirectory public () : This File indicate whether the directory.
    • public boolean isFile () this: File whether the documents indicated.
    • boolean createNewFile public () : if and only if a file with that name does not already exist, create a new empty file.
    • boolean the Delete public () : Deletes the File file or directory indicated.
    • boolean mkdir public () : Creating thus File directory indicated.
    • boolean mkdirs public () : Creating thus File directory represented, including any necessary but nonexistent parent directories of.

2.IO flow 

Transmitting data stream IO represents. The Java I / O operations mainly refers to the use of java.io package contents, input, output operations.

The data flow can be divided into the input stream (read) and output streams (write). The data can be divided into a byte stream and a stream of characters.

2.1 byte stream

Byte stream may transfer any file. The underlying transport is always arbitrary binary data file.

Byte output stream

java.io.OutputStreamAn abstract class is a output stream of bytes of all superclass.

OutputStream the basic method:

  • public void close() : Closes this output stream and releases associated with this stream any system resources.
  • public void flush() : Flushes this output stream and forces any buffered output bytes to be written.
  • public void write(byte[] b): The b.length byte to this output stream from the specified byte array.
  • public void write(byte[] b, int off, int len) : Write len bytes from the specified byte array to this output stream starts to output the offset off.
  • public abstract void write(int b) : The specified output stream of bytes.

java.io.FileOutputStream is a subclass of OutputStream.

FileOutputStream constructor:

  • public FileOutputStream(File file): Create a file output stream to write to the file represented by the specified File object.
  • public FileOutputStream(String name): Create a file output stream to write to the file name specified.
  • public FileOutputStream(File file, boolean append): Create a file output stream to write to the file represented by the specified File object.
  • public FileOutputStream(String name, boolean append): Create a file output stream to write to the file name specified.

FileOutputStream write method:

  • write (int b): Write byte.
  • write (byte [] b): Write byte array.
  • write (byte [] b, int off, int len): Write Specifies the length of the array.

Overwrite:

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

public
class TestFileOutputStream { public static void main(String[] args) throws IOException{ //使用File对象创建流对象 // File f = new File("1.txt"); // FileOutputStream fos = new FileOutputStream(f); //使用文件名称创建流对象 FileOutputStream fos2 = new FileOutputStream("2.txt"); //写入字节必须是byte数组 字符串串转byte数组 byte[] b = "abcde".getBytes(); //写入全部字节 // fos2.write(b); //写入指定字节 fos2.write(b,2,3);
     fos2.close(); } }

 

 

 

追加写入:

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

public class TestFileOutputStream {
    public static void  main(String[] args) throws IOException{
        //使用文件名称创建流对象
        FileOutputStream fos2 = new FileOutputStream("2.txt",true);

        //写入字节必须是byte    字符串串转byte数组
        byte[] b = "我是追加写入的内容".getBytes();
        //写入全部字节
        fos2.write(b);
       fos2.close();

    }

}

 

 

追加换行写入:

 

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

public class TestFileOutputStream {
    public static void  main(String[] args) throws IOException{
        //使用文件名称创建流对象
        FileOutputStream fos2 = new FileOutputStream("2.txt",true);

        //写入字节必须是byte数组    字符串串转byte数组
        byte[] b = "我是换行追加写入的内容".getBytes();
        //换行
        fos2.write("\r\n".getBytes());
        //写入全部字节
        fos2.write(b);
    
fos2.close();
} }

字节输入流

java.io.InputStream抽象类是表示字节输入流的所有类的超类,可以读取字节信息到内存中。

InputStream基本方法:

  • public void close() :关闭此输入流并释放与此流相关联的任何系统资源。
  • public abstract int read(): 从输入流读取数据的下一个字节。
  • public int read(byte[] b): 从输入流中读取一些字节数,并将它们存储到字节数组 b中 。

java.io.FileInputStream类是文件输入流,从文件中读取字节。

FileInputStream构造方法:

  • FileInputStream(File file): 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的 File对象 file命名。
  • FileInputStream(String name): 通过打开与实际文件的连接来创建一个 FileInputStream ,该文件由文件系统中的路径名 name命名。

创建文件输入流时,文件必须存在,否则会抛出FileNotFoundException。

FileInputStream写入方法:

  • read():每次读取一个字节。每次可以读取一个字节的数据,提升为int类型,读取到文件末尾,返回-1。
  • read(byte[] b):每次读取b的长度个字节到数组中,返回读取到的有效字节个数,读取到末尾时,返回-1 。
import java.io.IOException;
import java.io.FileInputStream;
public class TestFileInputStream {
    public static void main(String[] args) throws IOException{
        //创建文件流对象
        FileInputStream fis = new FileInputStream("1.txt");
        //读取
        while (fis.read()!= -1){
            int a = fis.read();
            System.out.println((char) a);
        }
     fis.close(); } }
import java.io.IOException;
import java.io.FileInputStream;
public class TestFileInputStream {
    public static void main(String[] args) throws IOException{
        //创建文件流对象
        FileInputStream fis = new FileInputStream("1.txt");
        //创建长度为2的字节数组
        byte[] b = new byte[2];
        //读取
        while (fis.read(b)!= -1){
            System.out.println(new String(b));
        }
        fis.close();

    }
}

2.2 字符流

当使用字节流读取文本文件时,可能会有一个小问题。就是遇到中文字符时,可能不会显示完整的字符,那是因为一个中文字符可能占用多个字节存储。所以Java提供一些字符流类,以字符为单位读写数据,专门用于处理文本文件。

字符输入流Reader

java.io.Reader抽象类是表示用于读取字符流的所有类的超类,可以读取字符信息到内存中。

Reader基本方法:

  • public void close() :关闭此流并释放与此流相关联的任何系统资源。
  • public int read(): 从输入流读取一个字符。
  • public int read(char[] cbuf): 从输入流中读取一些字符,并将它们存储到字符数组 cbuf中 。

java.io.FileReader类是读取字符文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

FileReader构造方法:

  • FileReader(File file): 创建一个新的 FileReader ,给定要读取的File对象。
  • FileReader(String fileName): 创建一个新的 FileReader ,给定要读取的文件的名称。

FileReader读取方法:

  • read方法,每次可以读取一个字符的数据,提升为int类型,读取到文件末尾,返回-1。
  • read(char[] cbuf),每次读取b的长度个字符到数组中,返回读取到的有效字符个数,读取到末尾时,返回-1。

字符输出流Write

java.io.Writer抽象类是表示用于写出字符流的所有类的超类,将指定的字符信息写出到目的地。

Writer基本方法:

  • void write(int c) 写入单个字符。
  • void write(char[] cbuf)写入字符数组。
  • abstract void write(char[] cbuf, int off, int len)写入字符数组的某一部分,off数组的开始索引,len写的字符个数。
  • void write(String str)写入字符串。
  • void write(String str, int off, int len) 写入字符串的某一部分,off字符串的开始索引,len写的字符个数。
  • void flush()刷新该流的缓冲。
  • void close() 关闭此流,但要先刷新它。

因为内置缓冲区的原因,如果不关闭输出流,无法写出字符到文件中。但是关闭的流对象,是无法继续写出数据的。如果我们既想写出数据,又想继续使用流,就需要flush 方法刷新缓存。

java.io.FileWriter类是写出字符到文件的便利类。构造时使用系统默认的字符编码和默认字节缓冲区。

FileWriter构造方法:

  • FileWriter(File file): 创建一个新的 FileWriter,给定要读取的File对象。
  • FileWriter(String fileName): 创建一个新的 FileWriter,给定要读取的文件的名称。

FileWriter方法类似于FileOutputStream。

2.3 缓冲流

缓冲流,也叫高效流,是对4个基本的FileXxx 流的增强,所以也是4个流,按照数据类型分类:

  • 字节缓冲流BufferedInputStreamBufferedOutputStream

  • 字符缓冲流BufferedReaderBufferedWriter

缓冲流的基本原理,是在创建流对象时,会创建一个内置的默认大小的缓冲区数组,通过缓冲区读写,减少系统IO次数,从而提高读写的效率。

我们只需要使用相应构造方法即可,其他读写操作方法和基本流一样。

字节缓冲流构造方法:

  • public BufferedInputStream(InputStream in) :创建一个 新的缓冲输入流。
  • public BufferedOutputStream(OutputStream out): 创建一个新的缓冲输出流。

字符缓冲流构造方法:

  • public BufferedReader(Reader in) :创建一个 新的缓冲输入流。
  • public BufferedWriter(Writer out): 创建一个新的缓冲输出流。

2.4 转换流

文件存在不同的编码,读取文件时,如果未使用IDEA默认编码,就会导致读取结果异常,出现乱码。

InputStreamReader类

转换流java.io.InputStreamReader,是Reader的子类,是从字节流到字符流的桥梁。它读取字节,并使用指定的字符集将其解码为字符。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法:

  • InputStreamReader(InputStream in): 创建一个使用默认字符集的字符流。
  • InputStreamReader(InputStream in, String charsetName): 创建一个指定字符集的字符流。

OutputStreamWriter类

转换流java.io.OutputStreamWriter ,是Writer的子类,是从字符流到字节流的桥梁。使用指定的字符集将字符编码为字节。它的字符集可以由名称指定,也可以接受平台的默认字符集。

构造方法:

 

  • OutputStreamWriter(OutputStream in): 创建一个使用默认字符集的字符流。
  • OutputStreamWriter(OutputStream in, String charsetName): 创建一个指定字符集的字符流。

2.5 序列化

Java 提供了一种对象序列化的机制。用一个字节序列可以表示一个对象,该字节序列包含该对象的数据对象的类型对象中存储的属性等信息。字节序列写出到文件之后,相当于文件中持久保存了一个对象的信息。反之,该字节序列还可以从文件中读取回来,重构对象对它进行反序列化。对象的数据对象的类型对象中存储的数据信息,都可以用来在内存中创建对象。

ObjectOutputStream类

java.io.ObjectOutputStream 类,将Java对象的原始数据类型写出到文件,实现对象的持久存储。

构造方法:

  • public ObjectOutputStream(OutputStream out): 创建一个指定OutputStream的ObjectOutputStream。

使用方法:

  • public final void writeObject (Object obj) : 将指定的对象写出。

序列化要求:

  • 该类必须实现java.io.Serializable 接口,Serializable 是一个标记接口,不实现此接口的类将不会使任何状态序列化或反序列化,会抛出NotSerializableException
  • 该类的所有属性必须是可序列化的。如果有一个属性不需要可序列化的,则该属性必须注明是瞬态的,使用transient 关键字修饰。

ObjectInputStream类

ObjectInputStream反序列化流,将之前使用ObjectOutputStream序列化的原始数据恢复为对象。

构造方法:

  • public ObjectInputStream(InputStream in): 创建一个指定InputStream的ObjectInputStream。

如果能找到一个对象的class文件,我们可以进行反序列化操作,调用ObjectInputStream读取对象的方法:

  • public final Object readObject () : 读取一个对象。

当JVM反序列化对象时,能找到class文件,但是class文件在序列化对象之后发生了修改,那么反序列化操作也会失败,抛出一个InvalidClassException异常。发生这个异常的原因如下:

 

  • 该类的序列版本号与从流中读取的类描述符的版本号不匹配
  • 该类包含未知数据类型
  • 该类没有可访问的无参数构造方法

 

2.7 打印流

java.io.PrintStream类,该类能够方便地打印各种数据类型的值,是一种便捷的输出方式。

PrintStream类

构造方法:

  • public PrintStream(String fileName): 使用指定的文件名创建一个新的打印流。

System.out就是PrintStream类型的,只不过它的流向是系统规定的,打印在控制台上。我们可以使用 System.setOut()改变流向。

import java.io.IOException;
import java.io.PrintStream;
public class TestPrintStream {
    public static void main(String[] args) throws IOException{
        // 创建打印流,指定文件的名称
        PrintStream ps = new PrintStream("1.txt");
        // 设置系统的打印流流向,输出到ps.txt
        System.setOut(ps);
        // 调用系统的打印流,ps.txt中输出97
        System.out.println(97);
        
    }
}

 

 

温馨提示

  • 如果您对本文有疑问,请在评论部分留言,我会在最短时间回复。
  • 如果本文帮助了您,也请评论关注,作为对我的一份鼓励。
  • 如果您感觉我写的有问题,也请批评指正,我会尽量修改。

 

Guess you like

Origin www.cnblogs.com/lyxdw/p/11672800.html