Android game programming-File Processing

Source: Internet
Author: User

The following are all converted from the android game programming entry-level classic. For details, refer to the source. game programming must not only use mobile phone memory but also access external storage space, mainly access the SD card. Read the resource file first.

We know that assets/and Res/folders are used to store files that can be used in applications.

Assets/is used to store files (such as configuration files or audio files) required by various applications. These files are packaged in Android applications.

Res/contains various resource files required by the application, such as icons, string files for internationalization, and XML files for interface layout. They are also packaged in application files.

In this case, we do not use Res/folders because it imposes restrictions on the construction of file sets. The assets/directory is where we store them, regardless of the hierarchical folder.

Files in the assets/folder are displayed through an assetmanager class. We can reference this manager in the application, as shown below:

Assetmanager = context. getassets ();

Once we get assetmanager, we can easily open the file:

Inputstream = assetmanager. Open ("DIR/dir2/filename.txt ");

This method returns a normal JAVA input stream, inputstream, through which we can read any type of files. The unique parameter of assetmanager. open () method is the file name relative to the asset directory. If the path is DIR/dir2/filename.txt, It is assets/DIR/dir2/filename.txt in eclipse.

Now we load the TXT file from a texts subdirectory under the assets/directory and display it in textview.

The Code is as follows:

package org.example.ch04_android_basics;import;import;import;import;import android.content.res.AssetManager;import android.os.Bundle;import android.widget.TextView;public class AssetsTest extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);TextView textView = new TextView(this);setContentView(textView);AssetManager assetManager = getAssets();InputStream inputStream = null;try{inputStream ="texts/myawesometext.txt");String text = loadTextFile(inputStream);textView.setText(text);}catch(IOException e){textView.setText("Couldn't load file");}finally{if(inputStream != null)try{inputStream.close();}catch(IOException e){textView.setText("Couldn't close file");}}}public String loadTextFile(InputStream inputStream) throws IOException{ByteArrayOutputStream byteStream = new ByteArrayOutputStream();byte[] bytes = new byte[4096];int len = 0;while((len = > 0)byteStream.write(bytes, 0, len);return new String(byteStream.toByteArray(), "UTF-8");}}

The running effect is as follows:

Loadtextfile (), a small method, is used to read all bytes from inputstream, convert all bytes into strings, return, and use UTF-8 encoding.

Next we need to access the external storage files. Sometimes we need to save some information permanently and reload them later.

The first thing to do is to request the actual access permission to the external bucket. You must add this permission to the <uses-Permission> element of the configuration file, for these permissions, refer to the android game programming manifest file preparation. Next, we need to check whether the devices used have useful external storage space.

String state = environment. getexternalstoragestate ();

We get a string. The environment class defines many constants, one of which is called environment. media_mounted, which is also a string. If the returned string is equal to this constant, we have all the permissions to read and write the external bucket. Note that the equals () method must be used to compare the two strings, and the referenced equations cannot work under any circumstances. For the difference between the equals () method and = in string, refer.

Once we determine that the external bucket can be accessed, we need to obtain the name of its root directory. If we want to access a specific file, we need to specify it relative to the root directory.

File externaldir = environment. getexternalstoragedirectory (); get the root directory

Now you can write a file on the SD card, read it and display it on textview, and then delete the file. The Code is as follows:

package org.example.ch04_android_basics;import;import;import;import;import;import;import;import android.os.Bundle;import android.os.Environment;import android.widget.TextView;public class ExternalStorageTest extends Activity {@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);TextView textView = new TextView(this);setContentView(textView);String state = Environment.getExternalStorageState();if(!state.equals(Environment.MEDIA_MOUNTED)){textView.setText("No external storage mounted");}else{File externalDir = Environment.getExternalStorageDirectory();File textFile = new File(externalDir.getAbsolutePath()+ File.separator + "text.txt");try{writeTextFile(textFile, "This is test. Roger");String text = readTextFile(textFile);textView.setText(text);if(!textFile.delete()){textView.setText("Couldn't remove temporary file");}}catch(IOException e){textView.setText("Something went wrong! " + e.getMessage());}}}private void writeTextFile(File file, String text) throws IOException{BufferedWriter writer = new BufferedWriter(new FileWriter(file));writer.write(text);writer.close();}private String readTextFile(File file) throws IOException{BufferedReader reader = new BufferedReader(new FileReader(file));StringBuilder text = new StringBuilder();String line;while((line = reader.readLine()) != null){text.append(line);text.append("\n");}reader.close();return text.toString();}}

The running effect is as follows:

From this we can see that we can easily delete all files on external devices. Therefore, when downloading and installing apps that require SD card permissions from the Android Market, you must think twice. Once the application is installed, it has full control over your 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: 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.