Android SD card Simple file read and write operation

Source: Internet
Author: User
Tags ultraedit

First, if you want to use SDcard for storage in your program, we have to set the following permissions on the Androidmanifset.xml file:

< Create and delete file permissions!--sdcard---    <uses-permission android:name="android.permission.MOUNT_ Unmount_filesystems"/>   <!--write data to SDcard permissions--   <uses-permission android:name= " Android.permission.WRITE_EXTERNAL_STORAGE "/>

Several static methods under the Environment class are then used when reading and writing with SDcard:

1:getdatadirectory () Get to the data directory in Android (Data folder in SD card)
2:getdownloadcachedirectory () gets to the downloaded cache directory (the download folder in the SD card)
3:getexternalstoragedirectory () Gets the directory to the external store generally refers to SDcard (/STORAGE/SDCARD0)
4:getexternalstoragestate () Gets the current state of the external settings generally refers to sdcard, the more commonly used should be media_mounted (sdcard exist and can read and write) and some other states, you can find in the document.

5:getrootdirectory () get to Android Root path

OK, here is the specific operation, look directly at the code:

1. Determine if the SD card exists

/* *  * Determine if sdcard is present [when there is no external SD card, the built-in ROM is also recognized as an SD card]  *   * @return  * * Public   Static Boolean issdcardexist () {      return  environment.getexternalstoragestate (). Equals (              environment.media_mounted);  }

2. Get the SD card root directory

/** * Get the SD card root directory path * * @return*/   Public StaticString Getsdcardpath () {Boolean exist=issdcardexist (); String Sdpath=""; if(exist) {Sdpath=environment.getexternalstoragedirectory (). GetAbsolutePath (); } Else{Sdpath="not used"; }      returnSdpath; }

3. Get the default file storage path

/** * Get the default file path * * @return*/   Public Staticstring Getdefaultfilepath () {string filepath=""; File File=NewFile (Environment.getexternalstoragedirectory (),"Abc.txt"); if(File.exists ()) {filepath=File.getabsolutepath (); } Else{filepath="not used"; }      returnfilepath; } 

4-1, read the file using FileInputStream

Try{le file=NewFile (Environment.getexternalstoragedirectory (),"Test.txt"); FileInputStream is=Newfileinputstream (file); byte[] B =New byte[Inputstream.available ()];  is. Read (b); String result=NewString (b); System. out. println ("Read success:"+result); } Catch(Exception e) {e.printstacktrace (); }

4-2, read the file using Bufferreader

Try{File File=NewFile (Environment.getexternalstoragedirectory (), default_filename); BufferedReader BR=NewBufferedReader (Newfilereader (file)); String ReadLine=""; StringBuffer SB=NewStringBuffer ();  while((ReadLine = Br.readline ())! =NULL) {System. out. println ("ReadLine:"+ReadLine);      Sb.append (ReadLine);      } br.close (); System. out. println ("Read success:"+sb.tostring ()); } Catch(Exception e) {e.printstacktrace (); }

5-1, write to file using FileOutputStream

Try{File File=NewFile (Environment.getexternalstoragedirectory (), default_filename); FileOutputStream Fos=Newfileoutputstream (file); String Info="I am a chinanese!";             Fos.write (Info.getbytes ());      Fos.close (); System. out. println ("Write success:"); } Catch(Exception e) {e.printstacktrace (); }

5-2, write to file using BufferedWriter

Try{File File=NewFile (Environment.getexternalstoragedirectory (), default_filename); //The second parameter is about whether to add content in a append wayBufferedWriter BW =NewBufferedWriter (NewFileWriter (file,true)); String Info="Hey, Yoo,bitch";      Bw.write (info);      Bw.flush (); System. out. println ("Write Success"); } Catch(Exception e) {e.printstacktrace (); }

Read and write we all realized, seemingly very simple appearance, but we now want to do a data collation every 30 seconds, and then write them into our TXT file, but I want to be able to write at the end of the last time, so that on the computer through the text open, you can see each row of data.

This actually requires that every time we write the data, there must be a newline operation symbol, such as: \ n, and Io read and write can be appended to the file.

At first I was very stupid to think, before each write, read the file and generate a StringBuffer, and then append, and then write .... This approach results in an IO operation of more than 2 times each time, read and write. In fact, the system is written to us with the append way, or to read the document AH!

BufferedWriter

With BufferedWriter, set the second argument to true when constructing bufferedwriter
BufferedWriter out = new BufferedWriter (New OutputStreamWriter (
New FileOutputStream (file, true));
Out.write (conent);

FileWriter

The second parameter in the constructor true indicates that the file is written in append form
FileWriter writer = new FileWriter (FileName, true);
Writer.write (content);
Writer.close ();

Open a random Access file stream, read and write
Randomaccessfile randomfile = new Randomaccessfile (fileName, "RW");
File length, number of bytes
Long filelength = Randomfile.length ();
Moves the write file pointer to the end of the file.
Randomfile.seek (filelength);
Randomfile.writebytes (content);
Randomfile.close ();

Question: When I wrote the file, I did not write it once, but obviously added a newline character (Bw.write ("\ n")), why can't I see the line break in the text Document of window? And in EditPlus or notepad++ can you see the effect after the line change?

New BufferedWriter (newtrue));   " Hey, Yoo,bitch " ;  Bw.write (info);  Bw.write ("\ n");  Bw.flush ();

What is this for?

This is caused by different encoding modes for Windows and Linux systems. The Android system is the Linux kernel, unlike Windows. Windows is a DOS encoding, the use of line break is a DOS newline character cr/lf, that is, we commonly known as \ r \ n, (if you do not understand can go to Baidu to escape characters, the general programmer will use this knowledge), and the Linux system line break is the Unix newline character LF, that is \ n, Apple's Mac system uses the Mac line-break CR, which is the \ r, and now I think you're pretty much understanding it. The document you build on your Android phone is definitely a UNIX line break, which is a \ n, but this document is opened with Notepad in Windows, because Windows Notepad is a DOS line break \ r \ n, so you're missing a \ r, so you can't identify a newline, Can only be recognized as a small box, the solution is very simple, you can use EditPlus or UltraEdit software to open, UltraEdit can also convert these encoding mode, converted to DOS mode.

So, we just need to add: \ r \ n

New BufferedWriter (newtrue));   " Hey, Yoo,bitch " ;  Bw.write (info);  Bw.write ("\ r \ n");  

Android SD card Simple file read and write operation

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.