编程知识 cdmana.com

Android foundation - file operation

Common methods

Method paraphrase
getFilesDir() obtain APP File path
getCacheDir() obtain APP Temporary file path

Get project path

package com.example.myapplication;
import android.content.Context;
import android.os.Bundle;
import android.app.Activity;

public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //  preservation Activity The state of   11
        super.onCreate(savedInstanceState);
        //  Load view 
        setContentView(R.layout.activity_main);

        //  Run the get path function , Incoming context  Context  object 
        String path = project_path(this);
        System.out.println(" The path obtained is :" + path);
    }
    //  Custom access path function , Parameter is context  Context  object 
    public static String project_path(Context context) {
        //  adopt  context  Get the current project path 
        String path = context.getFilesDir().getPath();
        return path;
    }
}

APP Store and access examples

AndroidManifest.xml

Here, in <uses-permission> In the label APP The required authority to authorize , And Android 9 The above needs to be in <application> Permission is allowed in , such as android:requestLegacyExternalStorage="true"

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplication">
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
<application android:allowBackup="true"
    android:label="@string/app_name"
    android:icon="@mipmap/ic_launcher"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@android:style/Theme.Wallpaper.NoTitleBar"
    android:requestLegacyExternalStorage="true"
    >
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>
</manifest>

MainActivity.java

This is where the main logic execution and execution state feedback are performed

package com.example.myapplication;
import android.os.Bundle;
import android.app.Activity;
import android.os.Environment;

public class MainActivity extends Activity{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //  preservation Activity The state of 
        super.onCreate(savedInstanceState);
        //  Load view 
        setContentView(R.layout.activity_main);
        //  Get project path 
        String pro_path = File_Tool.project_path(this);

        // ###### 【 Text writing 】 ######
        //  Sample text 
        String Str = " The dog is fishing by the river ";
        //  Absolute path of text storage 
        String str_path = pro_path + "/ String test text .txt";
        //  Perform a text write operation 
        File_Tool.str_txt(Str,str_path);

        // ###### 【sd Card text writing 】 ######
        //  Sample text 
        String Str2 = " The cat is catching butterflies in the grass ";
        //  obtain SD Card storage path 
        String sd_path = Environment.getExternalStorageDirectory()+"/";
        System.out.println(" The memory card path is :"+ sd_path);
        String wsd_path = sd_path + "123.txt";
        //  Perform a text write operation 
        File_Tool.str_txt(Str2,wsd_path);


        // ###### 【 Array storage 】 ######
        //  Sample array 
        String[] arr = {" kitten "," puppy "," Piglets "};
        //  Absolute path of text storage 
        String arr_path = pro_path + "/ Array test text .txt";
        //  Perform a text write operation 
        File_Tool.arr_txt(arr,arr_path);

        //  Read the file 
        File_Tool.read_txt(str_path);
        File_Tool.read_txt(arr_path);
        File_Tool.read_txt(wsd_path);
    }
}

File_Tool.java

And MainActivity.java Custom tool class of the same level directory , Contains the methods that the main class needs to call

package com.example.myapplication;
import android.content.Context;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class File_Tool {
    /**
     *  File tool class 
     **/
    public static String project_path(Context context) {
        /**【 Get path 】*/
        //  adopt  context  Get the current project path 
        String path = context.getFilesDir().getPath();
        return path;
    }

    public static Boolean str_txt(String str,String path){
        /**【 The text is written into app Internal storage 】*/
        try {
            //  Create byte output stream object 
            OutputStream os = new FileOutputStream(path);
            os.write(str.getBytes());                       //  Output data to the specified document through the output stream ( string  Types need to be transformed )
            os.close();
            System.out.println(" The text file was written successfully , The path is a :" + path);
            return true;
        } catch (IOException e) {
            System.out.print("\n【 The text is written into app Internal storage 】 Failure \n");
            return false;
        }
    }

    public static Boolean arr_txt(String[] arr, String path){
        /**【 Array written to txt】*/
        try {
            //  Create byte output stream object 
            OutputStream os = new FileOutputStream(path);
            //  Traverse the array and write it to the file 
            for(String i:arr){
                os.write(String.valueOf(i).getBytes());   // String  String types need to be converted 
            }
            os.close();
            System.out.println(" Array file written successfully , The path is a :" + path);
            return true;
        } catch (IOException e) {
            System.out.print("\n【 Array written to txt】 Failure \n");
            return false;
        }
    }

    public static Boolean read_txt(String path){
        /**【 Read file contents 】*/
        try {
            //  Create byte input stream object 
            InputStream is = new FileInputStream(path);
            //  Convert to character stream object 
            InputStreamReader reader = new InputStreamReader(is,"UTF-8");
            //  establish  BufferedReader  Buffer character stream 
            BufferedReader br = new BufferedReader(reader);

            // BufferedReader  Buffer character stream , Get the characters 
            String b;                                  //  Define the variable to record the bytes read each time 
            while (( b = br.readLine()) != null ){
                System.out.println(" The current value is :" + b);
            }
            //  Close the resource file , Avoid wasting server resources 
            is.close();
            reader.close();
            br.close();
            return true;
        } catch (IOException e) {
            // When multiple exceptions are thrown , Child exceptions are thrown before the parent exception .
            System.out.print("\n【 Read file contents 】 Failure \n");
            return false;
        }
    }
}

版权声明
本文为[ZHAO_JH]所创,转载请带上原文链接,感谢

Scroll to Top