A concrete instance of a Java IO stream file being read and written

  • 2020-04-01 02:39:18
  • OfStack

Quote:

The operation about Java IO stream is very common, basically every project will use, every encounter is to go to the Internet to look for it, tried and tested. Suddenly a colleague asked me last time Java file read, I suddenly meng first reaction is to find on the net, although also can be found, but the feeling is not very steadfast, so take time to took a look today some Java IO flow operation, still feeling very fruitful, summarizes some information, by the way, convenient after further study...

Classification of IO streams :
1. According to the data object of the stream:
High-end streams: all in-memory streams are high-end streams, such as InputStreamReader ;
Low stream: all streams in external devices are low stream, such as InputStream, OutputStream
How do you distinguish all stream objects whose suffixes contain Reader or Writer from those whose suffixes contain Reader or Writer

2. According to the flow of data:
Output stream: is used to write data, is by the program (memory) --> The equipment
Input stream: is used to read the data, is by the external device --> Program (memory)
How to distinguish between: generally speaking, Input stream has Input, output stream has Output ;

3. According to the format of the stream data:
Byte stream: a stream that processes binary data such as sound or pictures, such as an InputStream
Character stream: a stream that processes textual data, such as a TXT file, such as InputStreamReader ;
How to distinguish between high and low end streams, all low end streams are byte streams, and all high end streams are character streams

4. According to the packaging process of stream data:
Raw flow: in the process of instantiating an object of a flow, a flow that does not need to pass in another flow as an argument to its own constructor is called a raw flow.
Wrapper flow: in the process of instantiating the object of the flow, another flow needs to be passed in as a parameter of its own construction method, which is called a wrapper flow.
How to distinguish: all the low end flow is the original flow, all the high end flow is the packaging flow

Inheritance of IO stream objects (as shown below) :
< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201312/20131220172328931.jpg" >

Here are some specific code examples:

The file is read in bytes


public class ReadFromFile {
    
    public static void readFileByBytes(String fileName) {
        File file = new File(fileName);
        InputStream in = null;
        try {
            System.out.println(" Read the contents of the file in bytes, one byte at a time: ");
            //Read one byte at a time
            in = new FileInputStream(file);
            int tempbyte;
            while ((tempbyte = in.read()) != -1) {
                System.out.print(tempbyte);
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
            return;
        }
        try {
            System.out.println(" Read the contents of the file in bytes, read more than one byte at a time: ");
            //Read more than one byte at a time
            byte[] tempbytes = new byte[100];
            int byteread = 0;
            in = new FileInputStream(fileName);
            ReadFromFile.showAvailableBytes(in);
            //Read multiple bytes into a byte array. Byteread is the number of bytes read at once
            while ((byteread = in.read(tempbytes)) != -1) {
                System.out.print(tempbytes, 0, byteread);
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e1) {
                }
            }
        }
    }

Read the file by character


  
    public static void readFileByChars(String fileName) {
        File file = new File(fileName);
        Reader reader = null;
        try {
            System.out.println(" Read the contents of the file in characters, one character at a time: ");
            //Read one character at a time
            reader = new InputStreamReader(new FileInputStream(file));
            int tempchar;
            while ((tempchar = reader.read()) != -1) {
                //For Windows, rn represents a newline when the two characters are together.
                //But if the two characters are displayed separately, the lines are changed twice.
                //So, block out r, or block out n. Otherwise, there will be many more blank lines.
                if (((char) tempchar) != 'r') {
                    System.out.print((char) tempchar);
                }
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            System.out.println(" Read the contents of the file in character units, read more than one character at a time: ");
            //Read more than one character at a time
            char[] tempchars = new char[30];
            int charread = 0;
            //Because it is read as a character, a stream of characters is needed
            reader = new InputStreamReader(new FileInputStream(fileName));
            //Read more than one character into a character array, charread is the number of characters read at once
            while ((charread = reader.read(tempchars)) != -1) {
                //Also block out r not show
                if ((charread == tempchars.length)
                        && (tempchars[tempchars.length - 1] != 'r')) {
                    System.out.print(tempchars);
                } else {
                    for (int i = 0; i < charread; i++) {
                        if (tempchars[i] == 'r') {
                            continue;
                        } else {
                            System.out.print(tempchars[i]);
                        }
                    }
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

Read the file by line


  
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println(" Read the contents of the file in action units, one line at a time: ");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            //Read in one line at a time until null is read in for the end of the file
            while ((tempString = reader.readLine()) != null) {
                //According to the line Numbers
                System.out.println("line " + line + ": " + tempString);
                line++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }

Writes the contents of one file to another file (in lines)


public class FileTest {
public static void main(String[] args)   {
 File  file=new File("c:\test.txt");
 BufferedReader read=null;
 BufferedWriter writer=null;
 try {
   writer=new BufferedWriter(new  FileWriter("c:\zwm.txt"));
 } catch (IOException e1) {
  e1.printStackTrace();
 }
 try {
   read=new BufferedReader(new  FileReader(file));
   String tempString = null;
   while((tempString=read.readLine())!=null){
    writer.append(tempString);
    writer.newLine();//A newline
    writer.flush();//You need to clear the buffer of the stream in time in case the file is too large to write to
   }
   read.close();
   writer.close();
   System.out.println(" File write complete ...");
 } catch (IOException e) {
  e.printStackTrace();
 }

}
}


Related articles: