Use Java IO package for file read and write operations

Source: Internet
Author: User

2017-10-30

The interview in the previous days when the exam two questions, are related to the Java Foundation:

    • Use Java IO package to read and write files;
    • Use JDBC to get the data.

It is a pity that I could not remember the basic knowledge, so it is necessary to tidy up and consolidate this knowledge.

In this summary, I will summarize the read-write file operation of IO package through the two parts of code and text interpretation .

Scene

For example, there is a 1.txt file on the desktop, which is a row of random numbers separated by commas. Write a Java program to read the file and sort in descending order, and write to the 2.txt file (if it is not new). Limited IO packets.

Examining Knowledge points
    • Read file
    • Conversion between a string and an integer array
    • Sorting algorithms
    • Write a file
code Example

I will also host code on the cloud platform, can go to reference: Https://gitee.com/jinglun404/io-demo

1 ImportJava.io.*;2 3  Public classMain {4 5      Public Static voidMain (string[] args) {6String FilePath = "C:\\users\\asuss\\desktop\\1.txt";7 8 ReadFile (filePath);9     }Ten  One     //Read File Method A      Public Static voidreadFile (String filePath) { -         Try { -String encoding = "UTF-8"; the             //1. Get the File Object -File File =NewFile (filePath); -  -             if(File.isfile () && file.exists ()) {//determine if a file exists +                 //2.File Object->fileinputstream object->inputstreamreader Object -InputStreamReader Read =NewInputStreamReader (NewFileInputStream (file), encoding); +System.out.println ("read:" + read);//Read:[email protected] A  at                 //3. Obtaining BufferedReader objects from InputStreamReader objects -BufferedReader BufferedReader =NewBufferedReader (read); -System.out.println ("BufferedReader:" + BufferedReader);//Bufferedreader:[email protected] -  -                 //4. Read the contents of the file as a string through the BufferedReader object -String Linetext =NULL; in                  while((Linetext = Bufferedreader.readline ())! =NULL) { -System.out.println ("Linetext:" + linetext);//linetext:1,1,4,5,23,12,13,35,345,34,67,5,3,90 to  +                     //splits the read string into a string array based on "," -string[] Stringnums = Linetext.split (","); the  *                     //converts an array of strings into an integer array for sorting $                     int[] Intnums =New int[stringnums.length];Panax Notoginseng                      for(inti = 0; i < stringnums.length; i++) { -Intnums[i] =NewInteger (Stringnums[i]); the                     } +  A                     //Call Sort Method the Mysort (intnums); +  -                     //converts an integer array to a string for writing to a file $String s = ""; $                      for(inti = 0; i < intnums.length; i++) { -s + = Intnums[i] + ","; -                     } thes = s.substring (0, S.length ()-1);//remove the last one "," - Wuyi                     //calling the Write file method the WriteFile (s); -                 } Wu read.close (); -  About}Else { $SYSTEM.OUT.PRINTLN ("Cannot find the specified file! "); -             } -}Catch(Exception e) { -SYSTEM.OUT.PRINTLN ("Error reading file! "); A e.printstacktrace (); +         } the     } -  $     //Write File Method the     Private Static voidWriteFile (String s) { theString WriteFile = "C:\\users\\asuss\\desktop\\2.txt"; the  the         //1. Get the File Object -File NewFile =NewFile (WriteFile); in  the         Try { the             if(!newfile.exists ()) { About                 //If the file does not exist, create a new file the newfile.createnewfile (); the             } the  +             //2. Obtaining a FileOutputStream object from a file object -FileOutputStream out =NewFileOutputStream (NewFile,true); theStringBuffer SB =NewStringBuffer ();Bayi Sb.append (s); the  the             //3. Write via FileOutputStream -Out.write (S.tostring (). GetBytes ("UTF-8")); - out.close (); the}Catch(IOException e) { the e.printstacktrace (); the         } the     } -  the     //bubble Sort, descending output the     Private Static voidMysort (int[] intnums) { the         inttemp = 0;94          for(inti = 0; i < intnums.length; i++) { the              for(intj = 0; J < intnums.length-i-1; J + +) { the                 if(Intnums[j] < Intnums[j + 1]) { thetemp =Intnums[j];98INTNUMS[J] = intnums[j + 1]; AboutIntnums[j + 1] =temp; -                 }101             }102         }103     }104}
Description

Read file

Using the Java IO package to read the file content, divided into several steps:

    1. Incoming file path generates an instance of the Files object
    2. Generating an FileInputStream object instance from a File instance
    3. Generating an InputStreamReader object instance from an FileInputStream object instance
    4. Generating an BufferedReader object instance from an InputStreamReader object instance
    5. reads a row of data from a file by the . ReadLine () method of the BufferedReader object instance

The general steps are as above, but why do we do so? My understanding is as follows:

    1. java file operations are based on the Files object, So the first step in reading a file operation is definitely to get an instance of a file object, so what kind of an instance does it get? This makes it easy to think of a file instance that needs to get the files we are reading . So here we need to pass in the file path parameter, to construct a files instance.
    2. Get an instance of File, our Java The program gets in touch with the file, and the next step is to read the file into memory to facilitate our Java program to follow.
    3. by generating FileInputStream object instance, we write the contents of the file in bytes to memory.
    4. But we can't read byte content , Therefore, the byte content stored in memory cannot be output directly. A continuation conversion is required.
    5. by generating InputStreamReader object instance, we read the in-memory byte content, then further generate the BufferedReader object instance, place the byte content in the buffer, and speed up the operation.
    6. Finally, take advantage of BufferedReader. The ReadLine () method converts the bytes into a string information that we can read and output.

Write file

The Java IO package is used to write files, which are similar to reading files, or even simpler, for example:

    1. Get the File object instance
    2. Getting an FileOutputStream object instance from a File instance
    3. Write byte data to a file using the FileOutputStream . Write () method

Of course it's just a thought. The implementation process can refer to my code logic.

Sorting logic

The number of the order, the implementation of a lot of methods, I use the usual bubble sort, specifically do not expand, there is a lot of information on the Internet. You can also refer to the logic of my Code.

 Reference website

Http://www.cnblogs.com/manongxiaojiang/archive/2012/10/13/2722068.html
https://segmentfault.com/q/1010000000359840
Https://www.ezloo.com/2008/03/jave_file_reader_writer.html

Use Java IO package for file read and write operations

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.