[Java] Java IO Files

Source: Internet
Author: User

Files

You can use FileInputStream or filereader to read into a file based on binary, which is based on text. They do not need to read the entire file, but can read bytes, or characters sequentially, in the order in which they are stored.

Using FileOutputStream or FileWriter, data can be written out to a file and stored in the order in which the data is written.

Randomaccessfile can jump into a file, read data, or write data to a file. Random Access does not mean that you are actually reading data from a random location, or writing data to a random location. Instead, it means that you can jump in the file, then read the data in the place where you stayed, and write the data. When the data is written, it overwrites the original data, not the data.

The file class is used to get the size, properties, and cannot be used to get the file contents.

File class

The file class in the Java IO API can access the underlying file system and get the information element of the file, that is, the information that is used to describe the file, such as file size, attributes, and so on. If you need access to file content, you need to use FileInputStream, Fileoutpustream, Randamaccessfile. In Java NIO, the file contents are read in using Java.nio.FileChannel.

To create an instance of a file object

        New File ("/tmp/tony/a.txt");

Check if the file exists

When you create a file object, the constructor does not make an error even if it does not exist.

        New File ("/tmp/tony/a.txt");         boolean isfileexist = File.exists ();

Create a Directory

The Mkdirs () method can create all folders that are not on the File path. In the following example, if the resources and previous directories already exist, and the AAA and BBB two-tier directories do not exist, mkdirs () creates aaa/and its subdirectories bbb/.

        New File ("/tmp/tony/aaa/bbb/");        Boolean issuccess = Folder.mkdirs ();

The mkdir () method will only be the innermost directory. The above example if you use MkDir (), BBB will not be created because there is no AAA directory and returns FALSE.

File size

        New File ("/tmp/tony/a.txt");         long size = File.length ();

Move files, rename

Changing the file name, moving the file location, is similar to the MV command in Linux using the Renameto () method.

        New File ("/tmp/tony/a.txt");                 boolean issuccess = File.renameto (new file ("/tmp/tony/aaa/xx.txt"));

deleting files

        New File ("/tmp/tony/a.txt");                File.delete ();

Enumerate the files in the directory

The list () method obtains all the file names under the directory, and the Listfiles () method obtains all the files in the directory, in the form of a Document object.

        New File ("/tmp/tony/a.txt");                 = file.list ();         = File.listfiles ();

FileInputStream and Fileoutputstreamfileinputstream

FileInputStream reads the contents of a file based on the stream, in bytes. FileInputStream is a subclass of Inputsteam.

            New FileInputStream ("/tmp/tony/a.txt");             int data = is.read ();              while (Data! =-1) {                System.out.print (char) data);                 = Is.read ();                }            Is.close ();

The FileInputStream constructors are:

A. Receiving a String type

            String FilePath = "/tmp/tony/a.txt";             New FileInputStream (FilePath);

B. Receive a File object as a parameter

            New File ("/tmp/tony/a.txt");             New FileInputStream (file);    

Read () method that reads one byte at a time and returns the int value corresponding to that byte

Read (byte[]) reads one byte array at a time

Close () closes the stream

FileOutputStream

Write data to a file

            New FileOutputStream ("/tmp/tony/b.txt");             os.write ("abcd\n". GetBytes ());

FileOutputStream Constructors

A. Receiving a parameter, String type

            New FileOutputStream ("/tmp/tony/a.txt");

B. Receive a parameter, File type

            New File ("/tmp/tony/b.txt");             New FileOutputStream (file);

C. receive two parameters. The first parameter is used to locate the file, String or file type, and the second parameter indicates whether to append or overwrite the original contents of the file when the data is written out.

            New true);    // Append Content New false);                  // Overwrite content

Wirte () write one byte at a time

Write (byte[]) writes out a byte array at a time

Flush () Brush writes the data to the FileOutputStream buffer to the hard disk.

Randomaccessfile

Randomaccessfile can jump to a location in a file and start reading and writing data. When the data is written out, it overwrites the original content of the file in that location, which is fileinputstream and FileOutputStream cannot achieve.

FileReader and Filewriterfilereader

FileReader reads the contents of the file according to the stream, based on the character, and is similar to FileInputStream. The difference is that FileInputStream is based on Byte, and FileReader is based on characters.

            New FileReader ("/tmp/tony/a.txt");             int data = reader.read ();                          while (Data! =-1) {                System.out.print (char) data);                 = Reader.read ();            }            Reader.close

Character Set encoding

FileReader uses the encoding set of the application's environment to decode the read-in data. If you write out the encoding set of the file and the encoding set when you read the file, it will cause garbled characters. The character set needs to be set up, not with FileReader, but with FileInputStream-based InputStreamReader.

            New FileInputStream ("/tmp/tony/b.txt");             New InputStreamReader (IS, "UTF-8");             int data = reader.read ();              while (Data! =-1) {                System.out.print (char) data);                 = Reader.read ();            }            Reader.close ();

FileWriter

FileWriter writes data to a file in the same way as stream, based on characters, similar to FileOutputStream. The difference is that Fileoutputsteam is based on Byte, and FileWriter is based on characters.

            New FileWriter ("/tmp/tony/c.txt");            Writer.write ("aaabbb\n");            Writer.close ();

Two arguments to the constructor, the first parameter is used to locate the file, the second parameter indicates whether to append or overwrite the contents of the file when writing the data to the file.

New true);  // appends to file  Newfalse//overwrites file

FileWriter cannot specify a specific set of character encodings when writing data. If you need to specify an encoding set, you do not use FileWriter, but instead use FileOutputStream-based outputsteamwriter.

            New FileOutputStream ("/tmp/tony/d.txt");             New OutputStreamWriter (OS, "UTF-8");            Wt.write ("aaa\n hello");            Wt.close ();

Resources

Java IO Tutorial, Jenkov

[Java] Java IO Files

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.