Android Read and write file operating procedures

Source: Internet
Author: User
Tags sqlite database
The code is as follows Copy Code

Data storage and access common ways:
File
Sharedpreferences (preference parameter setting)
SQLite database
Contents provider (content Provider)
Internet

Activity (context)
The Context.getcachedir () method is used to get the/data/data/<package Name>/cache directory
The Context.getfilesdir () method is used to get the/data/data/<package name>/files directory

The activity (context) provides a openfileoutput (Filename,mode) method for outputting data to a file;
The first parameter is used to specify a file name and cannot contain the path separator '/'
The second parameter is operation mode:
Context.mode_private: Private operation mode created files can only be accessed by this program, if the file does not exist, will be automatically created, in addition: the contents of the written file will overwrite the contents of the original file;
Context.mode_append: Mode checks whether the file exists, appends the content if it exists, or creates a new file;
Context.mode_readable: Indicates that the current file can be read by other applications;
Context.mode_writeable: Indicates that the current file can be written by another application;

If you want the file to be read and written by another application: Incoming (context.mode_readable+context.mode_writeable)
FileOutputStream OutStream = Context.openfileoutput (filename,context.mode_private);

Example

Write Data
public void WriteFile (String filename,string writestr{
try{

FileOutputStream fout =openfileoutput (FileName, mode_private);

byte [] bytes = Writestr.getbytes ();

Fout.write (bytes);

Fout.close ();
}

catch (Exception e) {
E.printstacktrace ();
}
}

Reading data
public string ReadFile (string fileName) {
String res= "";
try{
FileInputStream fin = openfileinput (fileName);
int length = fin.available ();
byte [] buffer = new Byte[length];
Fin.read (buffer);
res = encodingutils.getstring (buffer, "UTF-8");
Fin.close ();
}
catch (Exception e) {
E.printstacktrace ();
}
return res;

}

param file name, how to operate

Android has its own security model, and when the application (. apk) is installed, the system is assigned to a userid, and when the application accesses other resources such as files, it is matched UserID, by default, any file created by the application. Sharedpreferences, the database is private (the created file is stored in the/data/data/<package name>/files directory), and only the specified mode of operation is externally readable or writable to be accessible by other programs;

Read file:

<1>
FileInputStream instream = context.openfileinput (filename);
LOG.I (Tag,instream ...)

<2>
Path= "/data/data/<package name>/files/hello.txt";
File File = new file (path);
FileInputStream instream = new FileInputStream (file);
LOG.I (Tag,instream ...)

CTRL + SHIFT + X/Y case

To read file data from raw resource:

String res = "";
try{

To get the raw data stream in a resource
InputStream in = Getresources (). Openrawresource (R.raw.test);

Get the size of the data
int length = in.available ();

byte [] buffer = new Byte[length];

Reading data
In.read (buffer);

According to Test.txt encoding type to choose the appropriate encoding, if not adjusted will garbled
res = encodingutils.getstring (buffer, "BIG5");

Shut down
In.close ();

}catch (Exception e) {
E.printstacktrace ();
}

Now let me summarize an example

The code is as follows Copy Code

/**
* "File Operation"
*/
Package iwit.iwittest;

Import Java.io.FileInputStream;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.InputStreamReader;
Import Java.io.OutputStreamWriter;

Import Android.content.Context;
Import Android.widget.Toast;

/**
* @author Shine
* "File read, write"
*/
public class Fileoperate
{
/**
* "Read Files"
* @param context
* @param fileName
* @return
*/
Public String ReadText (context context,string fileName)
{
FileInputStream fIn = null;
InputStreamReader ISR = null;
char[] InputBuffer = new char[255];
String data = null;
Try
{
FIn =context.openfileinput (fileName);
ISR = new InputStreamReader (fIn);
Isr.read (InputBuffer);
data = new String (inputbuffer);
Toast.maketext (Context, "read succeed", Toast.length_short). Show ();
}
catch (Exception e)
{
E.printstacktrace ();
Toast.maketext (context, ' not read ', Toast.length_short). Show ();
}
Finally
{
try {
Isr.close ();
Fin.close ();
}
catch (IOException E)
{
E.printstacktrace ();
}
}
return data;
}

/**
* "Write to File"
* @param context
* @param fileName
* @param data
*/
public void WriteText (context context, String filename,string data)
{
FileOutputStream fout = null;
OutputStreamWriter OSW = null;

try{
Fout =context.openfileoutput (FileName, 1);
OSW = new OutputStreamWriter (fout);
Osw.write (data);
Osw.flush ();
Toast.maketext (Context, "saved", Toast.length_short). Show ();
}
catch (Exception e)
{
E.printstacktrace ();
Toast.maketext (context, ' not saved ', Toast.length_short). Show ();
}
Finally
{
try {
Osw.close ();
Fout.close ();
}
catch (IOException E)
{
E.printstacktrace ();
}
}
}
}

This allows you to read and write files.

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.