Java's File.separator

Source: Internet
Author: User
Tags create directory

First, the file class

The path delimiter (\) under Windows is not the same as the path delimiter (/) under Linux, and when the absolute path is used directly, the cross platform will report no Such file or Diretory exception.

File also has several static constants similar to separator, which are related to the system and should be used as much as possible in programming.

Ps:file file = new file ("G:" + file.separator + "Demo.txt");

The file class is the only class in the Java.io package that is related to the operation of the file itself, which refers to file creation, deletion, renaming, etc.

. Construction method: Public File (String pathName), passing in the full path, web development This way is more useful.

. Construction Method: Public file (file parent,string child), passing in the parent path and the subpath.

Basic file operations:

. Create a new file: public boolean createnewfile () throws IOException;

. Delete File: public boolean delete ();

. Determine if the file exists: public boolean exists ();

1234567891011121314151617 importjava.io.File;importjava.io.IOException;publicclassTestFile {        publicstaticvoidmain(String [] args) throws IOException{        File file = newFile("G:\\demo.txt");        System.out.println("file:"+file);        if(file.exists()){            file.delete();            System.out.println("执行了删除文件!");        }else{            file.createNewFile();            System.out.println("执行了创建文件");        }    }}

If you have a directory when you create a file, you need to create the directory before you can create the file.

. Locate the parent path: public File getparentfile ();

Create directory: (1) Public boolean mkdirs (); You can create a folder in a nonexistent directory and create a multilevel directory (this method is recommended for personal use)

(2) Public boolean mkdir (); folder can only be created in a directory that is already near

Import Java.io.file;import Java.io.ioexception;public class Testfile {public        static void Main (String [] args) throws ioexception{        File File = new file ("G:" + file.separator + "Test" + file.separator + "Testfile" + file.separator + "Demo.tx T ");        if (!file.getparentfile (). exists ()) {//file does not exist            File.getparentfile (). Mkdirs ();            System.out.println ("performed to create a multilevel directory");        }        if (file.exists ()) {//File exists            file.delete ();            SYSTEM.OUT.PRINTLN ("Executed the delete file! ");        } else{            file.createnewfile ();            SYSTEM.OUT.PRINTLN ("Executed creation file");}}}    

In addition to the basic file and folder operations described above, there are several ways to obtain file information:

. Determine if the path is a file: public boolean isfile ();

. Determine if the path is a folder: public boolean isdirectory ();

. Last modified: public long lastmodified ();

. get file Size: public long length ();

. modify file Name: public boolean renameto (file dest);

Import Java.io.file;import Java.math.bigdecimal;import Java.text.simpledateformat;public class TestFileOne {public St atic void Main (String [] args) {File file = new file ("G:" + file.separator + "Test" + file.separator + "testfile" + file        . Separator + "1.jpg"); if (file.exists ()) {System.out.println (File.isdirectory ())?            "Is folder": "Not a Folder"); System.out.println (File.isfile ()?            "is a file": "Not a document");            System.out.println ("Last modified:" +new SimpleDateFormat ("Yyyy-mm-dd HH:mm:ss"). Format (file.lastmodified ())); SYSTEM.OUT.PRINTLN ("File size:" + New BigDecimal ((File.length ()/(double) 1024/1024). Divide (                        New BigDecimal (1), 2,bigdecimal.round_half_up) + "M");                if (File.renameto ("G:" + file.separator + "Test" + file.separator + "Testfile" + file.separator + "hello.jpg")) {            System.out.println ("renaming succeeded");            }else{System.out.println ("rename failed"); }        }    }}

List all content in the specified folder:

Public File [] listfiles ();

Import Java.io.file;public class Testfiletwo {public    static void Main (String [] args) {        file File = new file ("G:" + File.separator + "Test");        if (file.exists () && file.isdirectory ()) {            file [] list = File.listfiles ();            for (int i = 0; i < list.length; i + +) {                System.out.println ("Files:" +list[i]);}}}    

Lists all files in the specified directory (containing files from all subdirectories), recursively calls

Import Java.io.file;public class Testfilethree {public    static void Main (String [] args) {        file File = new file ("G: "+ File.separator +" Test ");        print (file);    }        public static void print (file file) {        if (file.exists () && file.isdirectory ()) {            file [] files = File.listfiles ();            if (files.length > 0 && files = null) {for                (int i = 0; i < files.length; i++) {                    print (files[i]);//Recursive call                }            }        }        System.out.println (file);}    }

Two, the character stream and the character stream

Using the file class can only be done with the actions of the files themselves, but not with the operation of the content. If you want to do a file content operation, you can use two sets of streams:

. Byte Stream InputStream OutputStream

. Character Stream Reader writer

Regardless of which stream is used, the basic procedure is the same, taking file operations as an example:

. Determine the path to the action file

. Instantiate a byte stream or character stream class object by a byte stream or a subclass of a character stream

. For incoming and outgoing operations

. Close the stream, the flow is a resource operation, the resource operation must be closed

1, byte input stream: OutputStream

Java.io.OutputStream is the output that can make byte data (byte)

There are three write () methods in the OutputStream class:

• Output single byte: public void write (int b);

• Output all bytes: public void Write (byte [] b);

• Output Partial bytes: public void Write (byte [] b,int off,int len);

OutputStream is an abstract class, so you can instantiate it using subclasses. For file operations, you can use FileOutputStream, which has two common construction methods:

Public fileoutputstream (file file) throws FileNotFoundException, overlay;

Public fileoutputstream (File file, Boolean append) throws FileNotFoundException, append;

Output operation to overwrite the file:

Package Com.java.io;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.outputstream;public class Testfile {public    static void Main (String [] args) throws ioexception{        File fil E = new File ("G:" + file.separator + "Test" + file.separator + "Demo.txt");        if (!file.getparentfile (). exists ()) {            file.getparentfile (). Mkdirs ();        Instantiate        outputstream output = new FileOutputStream (file) for the parent class object through the subclass object of OutputStream;        The data to output        String msg = "Hello world.";        Converts a string to a byte array        byte [] data = Msg.getbytes ();        Output byte array        output.write (data);        Output.flush ();        Close        output.close ();    }}

Regardless of how many times it is executed, it is the overwrite of the current file. If you do not want to overwrite, you can create the FileOutputStream class object using the Append method

. Append content: OutputStream output = new FileOutputStream (file, true);

Single byte:

Package Com.java.io;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.outputstream;public class Testfile {public    static void Main (String [] args) throws ioexception{        File fil E = new File ("G:" + file.separator + "Test" + file.separator + "Demo.txt");        if (!file.getparentfile (). exists ()) {            file.getparentfile (). Mkdirs ();        Instantiate        outputstream output = new FileOutputStream (file) for the parent class object through the subclass object of OutputStream;        The data to output        String msg = "Hello world.\r\n";        Converts a string to a byte array        byte [] data = Msg.getbytes ();        Output byte array for        (int i = 0; i < data.length; i++) {            output.write (data[i]);        }        Close        output.close ();    }}

2, byte input stream: InputStream

There are three read () methods defined in the InputStream class:

• Read single byte: public int read () throws IOException;

Each time a read () operation reads a byte of data, the data is returned and INT returns 1 if the data has been read

Read content to byte array: public int read (byte [] b) throws IOException ();

Reads the contents into a byte array, returns the number of reads, and returns 1 if the read is complete

Read content to a partial byte array: public int read (byte [] b,int Off,int len) throws IOException ();

Reads the contents of the specified length into a byte array, returns the number of reads, and returns 1 if the read is complete

InputStream is an abstract class, so it can be instantiated using its subclasses. Use the FileInputStream subclass to complete its construction method:

Public fileinputstream (file file) throws FileNotFoundException;

Reading data using InputStream

Package Com.java.io;import Java.io.file;import Java.io.fileinputstream;import Java.io.inputstream;public class Testfileone {public    static void Main (string[] args) throws Exception {        file File = new file ("G:" +file.separator+ " Test "+file.separator+" Demo.txt ");        if (file.exists ()) {//file exists            inputstream input = new FileInputStream (file);            byte [] data = new byte[1024];//This array is used to accept all input data            int len = input.read (data),//To save to the array            System.out.println ("" +new String (data, 0, Len));            Input.close ();}}}    

Using while loop reading in real development

Package Com.java.io;import Java.io.file;import Java.io.fileinputstream;import Java.io.inputstream;public class Testfileone {public    static void Main (string[] args) throws Exception {        file File = new file ("G:" +file.separator+ " Test "+file.separator+" Demo.txt ");        if (file.exists ()) {//file exists            inputstream input = new FileInputStream (file);            byte [] data = new byte[1024];//This array is used to accept all input data            int temp = 0;//Define each read incoming data            int foot = 0;//Define Array corner label            //(temp = input . read ())! =-1 Determine if temp is equal to-1 if not then continue reading while            ((temp = Input.read ())! =-1) {                data[foot++] = (byte) temp;            }            Input.close ();            Print            System.out.println (new String (data, 0, foot));}}}    

3. Character output stream: Writer

The difference between the byte output stream and the character output stream is that the byte output stream is based on the byte type, and the character output stream is char-dominated, and the direct manipulation of string is supported

How to operate in the writer class:

• Output string: public void Write (String str) throws IOException;

• Output byte array: public void Write (char [] cbuf) throws IOException;

But writer is an abstract class, and if you use it for file operations, you must use the FileWriter subclass

Package Com.java.io;import Java.io.file;import java.io.filewriter;import java.io.ioexception;import java.io.Writer; public class Testfilewriter {public    static void Main (String [] args) throws ioexception{        File File = new file ("G: "+file.separator+" Test "+file.separator+" FileWrite.txt ");        if (!file.getparentfile (). exists ()) {            file.getparentfile (). Mkdirs ();        Writer out = new FileWriter (file);        String msg = "Hello world.";        Out.write (msg);        Out.close ();    }}

4. Character input stream

Reader is responsible for reading the character data, using the Read () method for reading, but not directly returning a read operation of type string

• Read data: public int read (char [] cbuf) throws IOException;

Package Com.java.io;import Java.io.file;import java.io.filereader;import java.io.ioexception;import java.io.Reader; public class Testfilewriterone {public    static void Main (String [] args) throws ioexception{        File File = new file ( "G:" +file.separator+ "Test" +file.separator+ "FileWrite.txt");        if (file.exists ()) {            Reader in = new FileReader (file);            char [] data = new char[1024];            int len = in.read (data);            In.close ();            System.out.println (New String (Data,0,len));}}}    

The two read operations are essentially different from each other, except that the character operation is String/char, while the byte operation is byte;

5. The difference between a byte stream and a character stream

• Character stream: The character stream is most convenient when the program is processed in Chinese;

• Byte stream: When the program processes binary data (pictures, music, movies) or network data transfer, or save to disk data must be bytes;

In addition to the above differences, the byte stream in the operation of the operation terminal directly with the interaction, and the character stream needs to pass through the buffer processing before you can operate, in OutputStream and writer two class output file as an example, if the OutputStream output can not close the output stream, However, if the output of the writer class is not closed, the data stored in the buffer will not output or force the buffer to flush.

Package Com.java.io;import Java.io.file;import java.io.filewriter;import java.io.ioexception;import java.io.Writer; public class Testwriter {public    static void Main (String [] args) throws ioexception{        File File = new file ("G:" +fi le.separator+ "Test" +file.separator+ "FileWrites.txt");        if (!file.getparentfile (). exists ()) {            file.getparentfile (). Mkdirs ();        Writer out = new FileWriter (file);        String msg = "Hello world,i am a programer.";        Out.write (msg);        Out.flush ();        Out.close ();    }}

The so-called buffer is a piece of memory, when the data is read into the memory area before the processing, so it can better handle the Chinese

Third, the conversion stream

Since there are both byte and character operation flows, the two operations flow can be converted to each other, mainly using two classes: InputStreamReader, OutputStreamWriter

InputStreamReader is a subclass of reader, so the InputStreamReader class object can be automatically transformed into a reader class instance.

OutputStreamWriter is a subclass of writer, so the OutputStreamWriter class object can be automatically transformed into a writer class instance.

Java's File.separator

Related Article

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.