java file operations (read and write operations)

java file operations (read and write operations)
java read and write operations are the only way to learn java development, the following read and write operations to the summary of java.

Can start out from the graph, java read and write operations (input and output) can be represented, in general, java divided into two read and write operations use the concept of "flow": character stream and byte stream.

What is the flow?

Stream is an abstract concept. When the Java program needs to read data from a data source, it will open a stream to the data source. The data source may be a file, memory, network, or the like. Similarly, when the program needs to output data to the same destination will open a stream, the destination data may be a file, memory, network, or the like. Flow is created in order to more easily handle the input and output data.

Then the byte stream and character stream what difference it there?

1. byte stream also called the raw data, converting the corresponding coding requires the user to read. Realized character stream is based on an automatic conversion will automatically converted into data according to the default character encoding JVM when reading data.

Stream processing unit 2. Character Unicode character is 2 bytes, respectively, operation of the character, a character string or an array, the byte stream processing unit is a byte, byte and byte array operation.

So the character stream is a Java Virtual Machine byte Unicode character is converted to 2-byte character unit is formed.

3. The stream of bytes may be used for any type of object, including the binary object, the character stream can process characters or strings, byte stream provides the function of any type of IO processing operation, but it can not directly handle Unicode characters, and character stream can be;

Based on the above difference, then under what circumstances with a character stream, under what circumstances it with a stream of bytes?

If audio files, pictures, songs, use a byte stream good point; if it is Chinese (text), the flow better with the characters;

Having said that, byte stream and character stream processing files in the end how to use it?

Shaoanwuzao, let us first look at the java, what steps is the input and output operations?

1 Use the File class to open a file

2 by a subclass of the byte stream or a character stream, the output of the position specification, note,

3 read / write operations

4 closes the input / output

IO operations are resource operations, we must remember to shut down

Byte stream:

1. Read data from the file in a byte stream mode.
2.package ioInJava.characterStream;

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

public class CharIo {

public static void main(String[] args) {

    // 第一种方式读文件,因为方法throws了异常,所以在这要捕获异常
    try {
        CharIo.readFromFileByByte();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
        System.out.println("找不到文件啊");
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("读不成功啊!");
    }

    System.out.println("===========================");

    // 第二种方式读文件
    try {
        CharIo.readFromFileByteTwo();
    } catch (IOException e) {
        e.printStackTrace();
        System.out.println("还是读不成功啊!");
    }

}

/**
 * 第一种方法读文件
 * 通过字符流读取文件中的数据
 * @throws IOException 
 */
public static void readFromFileByByte() throws IOException{
    File file = new File("abc.txt");
    // 如果文件不存在则创建文件
    if (!file.exists()) {
        file.createNewFile();
    }
    InputStream inputStream = new FileInputStream(file);
    // 这里定义了数组的长度是1024个字节,如果文件超出这字节,就会溢出,结果就是读不到1024字节以后的东西
    byte[] bs = new byte[1024];
    // 这里len获得的是文件中内容的长度
    int len = inputStream.read(bs);
    inputStream.close();
    System.out.println(new String(bs));
}

/**
 * 第二种方法读文件
 * 通过字符流读取文件中的数据
 * @throws IOException 
 */
public static void readFromFileByteTwo() throws IOException{
    // 注意这里的不同,File.separator是分隔符,这里指明绝对路径,即D盘根目录下的abc.txt文件
    File file = new File("d:" + File.separator+"abc.txt");
    // 如果文件不存在则创建文件
    if (!file.exists()) {
        file.createNewFile();
    }
    InputStream inputStream = new FileInputStream(file);
    // 这里也有不同,可以根据文件的大小来声明byte数组的大小,确保能把文件读完
    byte[] bs = new byte[(int)file.length()];
    // read()方法每次只能读一个byte的内容
    inputStream.read(bs);
    inputStream.close();
    System.out.println(new String(bs));
}

}
2. Write data to a file in accordance with the mode byte stream.
3.package ioInJava.byteStream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**

  • Do not be scared so much try and catch Austria, it is only because did not want throws on the main
  • @author wsg
    */
    public class WriteToFile {

    static void main public (String [] args) {
    File File = new new File ( "D:" + the File.separator + "write.doc");
    the OutputStream the outputStream = null;
    IF (File.Exists ()!) {
    the try {
    / / If the file is not found, a new on
    file.createNewFile ();
    } the catch (IOException E) {
    e.printStackTrace ();
    }
    }
    the try {
    // definition of the output stream, the stream write files
    outputStream = new FileOutputStream (file );
    } the catch (a FileNotFoundException E) {
    e.printStackTrace ();
    }
    data to be written to a file // define a
    String string = "Hell Java, Hello World, Hello, World!";
    // converts into a byte string type and it is present on the array
    byte [] = bs string.getBytes ();
    the try {
    // the data is written to file bs
    OutputStream.write (bs);
    } catch (IOException e) {
    e.printStackTrace();
    }

    try {
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    // =================到此,文件的写入已经完成了!
    
    // 如果想在文件后面追加内容的话,用下面的方法
    OutputStream outToFileEnd = null;
    try {
        outToFileEnd = new FileOutputStream(file,true);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }finally {// 这里利用了finally总会被执行的特性,索性把后面的代码都写在finally中
        String string2 = "Here I come!!";
        byte[] bs2 = string2.getBytes();
        try {
            outToFileEnd.write(bs2);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outToFileEnd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    }
    }
    1. Beginners generally very easy to become confused or unclear about inputstream and outpustream in the end which is read data, which is writing data to note here is that "reading and writing" is relative to the procedure itself, the main thing to remember clearly that all data required to provide to the program is processing the input data, of course, is inputstream, here in is to go in to the program inside, then the data it come naturally from the outside world (network, memory or file), then the file-specific, inputstream is to read files. On the contrary, all procedures have been processed data, of course, the matter out of the program, that is, out slightly, so outputstream is output, then the outflow from the program, only to the outside world (network, memory or file), for the document, that is, write it! (By the same token it can be operated for a character stream)

[In short, for the purposes of the program, in're into, out is out; in terms of this document, in read, out to write! ]

2.inputstream and OutputStream abstract class is not instantiated, it must instantiate a subclass (wherein FileInputStream and FileOutputStream use up) is performed using object-related operations.

3.InputStream inputStream = new FileInputStream (fileName) ; When using this command, the system will prompt an exception is thrown, because we believe that the above-defined file program is likely to exist, there may not exist, so the eclipse, to the two solutions, a direct statement throws an exception, resolved by the system itself; the other is to use try, catch structure to handle exceptions!
4.3. Write data to a file in a manner character streams.
5.package ioInJava.characterStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;

public class CharIo {

public static void main(String[] args) throws IOException {
    // 定义一个d盘根目录下的test文档,File.separator是分隔符
    // 下面这句代码,就算原本没有这个文件,也会在对应的目录创建一个文件
    File file = new File("D:" + File.separator + "test.docx");
    // 下面这也会抛出异常,这次我们为了代码结构清晰起见,直接throw给main吧
    Writer writer = new FileWriter(file);
    String string = "今天是教师节!";
    writer.write(string);
    // 在这一定要记得关闭流
    writer.close();
}

}
However, the above code there is a problem, for example, contained a definition of string2, call writer.write (string2) method again, you will find test the contents of the file will be overwrite the contents of string2, in order to achieve appended to the file contents tail, as follows, in fact, small change, one way to use it!
package ioInJava.characterStream;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Writer;

public class CharIo {

public static void main(String[] args) throws IOException {
    // 定义一个d盘根目录下的test文档,File.separator是分隔符
    // 下面这句代码,就算原本没有这个文件,也会在对应的目录创建一个文件
    File file = new File("D:" + File.separator + "test.docx");
    // 下面这也会抛出异常,这次我们为了代码结构清晰起见,直接throw给main吧
    // 这里改变了writer的类型,变成了追加型
    Writer writer = new FileWriter(file, true);
    String string = "今天是教师节!";
    writer.write(string);
    String string2 = "祝愿所有的老师教师节快乐!";
    writer.write(string2);;
    // 在这一定要记得关闭流
    writer.close();
}

}
4. Read data from the file in a manner of character stream.
package ioInJava.characterStream;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;

public class ReadFromFile {

public static void main(String[] args) throws IOException {
    File file = new File("d:" + File.separator + "test.docx");
    Reader reader = new FileReader(file);
    char[] cs= new char[1024];
    // 上面定义了一个大小为1024的char型数组,如果文件内容过大,程序就会报错,而不是只读到1024的大小
    reader.read(cs, 0, (int)file.length());
    System.out.println(cs);
    reader.close();
}

}
The above code can be read from the content of no more than 1024 characters, which is obviously not what we want, how to read a file of any size it! Then the easiest way is to increase the size of the array of space, you can use file.length get the file size, in order to define the size of the array! char [] cs = new char [ (int) file.length ()];

Of course, this is not the best way to see the following code:
Package Penalty for ioInJava.characterStream;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.io.Writer;

public class ReadFromFile {

public static void main(String[] args) throws IOException {
    try {
        // 声明一个可变长的stringBuffer对象
        StringBuffer sb = new StringBuffer("");

        /*
         * 读取完整文件
         */
        Reader reader = new FileReader("d:" + File.separator + "test.docx");
        // 这里我们用到了字符操作的BufferedReader类
        BufferedReader bufferedReader = new BufferedReader(reader);
        String string = null;
        // 按行读取,结束的判断是是否为null,按字节或者字符读取时结束的标志是-1
        while ((string = bufferedReader.readLine()) != null) {
            // 这里我们用到了StringBuffer的append方法,这个比string的“+”要高效
            sb.append(string + "/n");
            System.out.println(string);
        }
        // 注意这两个关闭的顺序
        bufferedReader.close();
        reader.close();

        /*
         * 完整写入文件
         */
        Writer writer = new FileWriter("d:" + File.separator + "test2.docx");
        BufferedWriter bw = new BufferedWriter(writer);
        // 注意这里调用了toString方法
        bw.write(sb.toString());
        // 注意这两个关闭的顺序
        bw.close();
        writer.close();

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

}

Guess you like

Origin blog.51cto.com/14467455/2430620