Android Learning one: file manipulation

Source: Internet
Author: User

Recently in the study of Android-related programming, for a new technology learning, I think it should be the same as other languages, such as C + + and C #, is also a file, network, multi-threaded and database and other learning. So I decided to start with the file, and now I'm going to list a little bit of the file:

Operation of files in 1.Java

There are two types of operations for files in Java: Byte type (Stream) and character type (Reader), but character types can be problematic when working with non-literal types of data.

Okay, the last piece of code:

/*** Copy of File *@paramSrcpath Source file path *@paramdestpath Destination file path *@throwsException throws an exception*/     Public Static voidCopy (string Srcpath, String destpath)throwsexception{File src=NewFile (Srcpath); File dest=NewFile (DestPath); InputStream input=NewBufferedinputstream (NewFileInputStream (SRC)); OutputStream Output=NewBufferedoutputstream (NewFileOutputStream (dest)); intLen = 0; byte[] buffer =New byte[1024];  while( -1! = (len =input.read (buffer))) {output.write (buffer,0, Len);        } output.close ();    Input.close (); }

The main function of this code is to copy the source file to the target file, it is important to note that the target file must specify a file name , if it is a path, error.

Newnew File (DestPath);

The meaning of these two sentences is to establish a connection with the file in order to allow the subsequent flow to be manipulated, and of course to specify the path to the file directly in the stream.

New Bufferedinputstream (new fileinputstream (SRC));

This is the declaration of the output stream, because the external file is imported into the program, so you need to use FileInputStream, which is understandable. So what does Bufferedinputstream do? Using Bufferedinputstream to decorate the fileinputstream, so that the normal file input stream with memory cache function, through the memory buffer to reduce the number of disk IO, see someone else's blog on the words, said clearly and took over. For Bufferedoutputstream, the effect is similar.
In addition, when Input.read () is processed to the end of the file, it returns-1, which determines whether the file reads the end. For Output.close (), the Flush method is called to write the cached data into the file, and finally remember to close the stream.

Here the exception is thrown directly, because this method is the logical layer, so exception handling is given to the business layer.

Operation of 2.Android files

Class Fileservice {    private Fileservice () {    }    throwsnew File (fileName);  New Bufferedoutputstream ( fileoutputstream (file)); Output.write (Content.getbytes ()); Output.close (); }}

Since the code can be used in Java, the code should be available in Android. However, an error occurred while executing:

Open File Error: Read Only file system open Failed:erofs

What is the reason for this? Later, on the stack overflow, the following passage was found:

You are not having access to the File-system root, which are what you ' re attempting to access. For your purposes, you can write to internal files new file ("Test.png"), which places the file in the Application-internal Storage--better yet, access it explicitly using Getfilesdir ().

Basically, the app does not have the system root permission, that is, I created the file directly at the root of the system, but the written app does not have the relevant permissions. But can be written on the phone's internal memory, through the Getfilesdir () to obtain the internal directory. The update code is as follows:

PackageOrg.tonny.util;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.OutputStream;ImportAndroid.content.Context;PublicFinalClassFileservice {private context context; public Fileservice (context context) {this.context = context;} public void write (string fileName, string content) throws Exception {File File = new File ( Context.getfilesdir () + file.separator + fileName); // establish connection OutputStream output = new Bufferedoutputstream (new  FileOutputStream (file)); Output.write (Content.getbytes ()); Output.close (); }}

After this modification, you can create the file. So whether Android provides another way to do the relevant operation, after some review, found that there are, the code is as follows:

 PackageOrg.tonny.util;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.FileReader;ImportJava.io.FileWriter;ImportJava.io.OutputStream;ImportAndroid.content.Context; Public Final classFileservice {Privatecontext Context;  PublicFileservice (Context context) { This. Context =context; }     Public voidWrite (string fileName, string content)throwsException {File file=NewFile (Context.getfilesdir () + file.separator + fileName);//Establish a connectionOutputStream output =NewBufferedoutputstream (Newfileoutputstream (file));        Output.write (Content.getbytes ());        Output.flush ();    Output.close (); }         Public voidWriteFile (string fileName, string content)throwsexception{outputstream Output=NewBufferedoutputstream (Context.openfileoutput (FileName, context.mode_private));        Output.write (Content.getbytes ());        Output.flush ();    Output.close (); }}

It is also possible to create files in the appropriate directory of the app.

Then you can store files in the internal memory of the file, how to store files on the SD card, the online example is more, the code is as follows:

 Public voidWritesdfile (string fileName, string content)throwsException {BooleanSdcardexist =environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED); if(!sdcardexist) {            //SD card does not exist, then exit            return; } File File=NewFile (Environment.getexternalstoragedirectory (). GetPath ()+ File.separator +fileName); OutputStream Output=NewBufferedoutputstream (Newfileoutputstream (file));        Output.write (Content.getbytes ());        Output.flush ();    Output.close (); }

Here, you need to determine if the SD card exists for further operation, and you need to configure it in the manifest file.

<android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>

The code is written, simple refactoring:

 PackageOrg.tonny.util;ImportJava.io.BufferedOutputStream;ImportJava.io.File;ImportJava.io.FileOutputStream;ImportJava.io.OutputStream;ImportAndroid.content.Context;Importandroid.os.Environment; Public Final classFileservice {Privatecontext Context;  PublicFileservice (Context context) { This. Context =context; }     Public voidWrite (string fileName, string content)throwsException {File file=NewFile (Context.getfilesdir () + file.separator + fileName);//Establish a connectionoper (file, content); }     Public voidWriteFile (string fileName, string content)throwsException {outputstream output=NewBufferedoutputstream (Context.openfileoutput (FileName, context.mode_private));        Output.write (Content.getbytes ());        Output.flush ();    Output.close (); }     Public voidWritesdfile (string fileName, string content)throwsException {BooleanSdcardexist =environment.getexternalstoragestate (). Equals (Android.os.Environment.MEDIA_MOUNTED); if(!sdcardexist) {            //SD card does not exist, then exit            return; } File File=NewFile (Environment.getexternalstoragedirectory (). GetPath ()+ File.separator +fileName);    Oper (file, content); }    /*** File Write operation * *@paramfile *@paramcontent *@throwsException*/    Private voidOper (file file, String content)throwsException {outputstream output=NewBufferedoutputstream (Newfileoutputstream (file));        Output.write (Content.getbytes ());        Output.flush ();    Output.close (); }}

As the study is still at a relatively shallow level, I have written a few simple examples. There is much more to be desired, such as file attributes, copying and reading, etc. are not written. There is also no overall description of the Android IO operation class structure, so the article is still a bit confusing. Alas, the first time I wrote it, it took a lot to rest.

Android Learning one: file manipulation

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.