Example of Android App writing data to internal and external storage

  • 2021-06-28 14:03:15
  • OfStack

File Storage (Internal Storage)
1Once the program is installed on the device, data/data/package name/is the internal storage space, which is kept secret from the outside world.
Context provides two ways to open input and output streams

FileInputStream openFileInput(String name) FileOutputStream openFileOutput(String name, int mode)

public class MainActivity extends Activity {

  private TextView show;
  private EditText et;
  private String filename = "test";
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    show = (TextView) findViewById(R.id.show);
    et = (EditText) findViewById(R.id.et);

    findViewById(R.id.write).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          FileOutputStream fos = openFileOutput(filename, Context.MODE_PRIVATE);
          //FileOutputStream Is a byte stream, if it is writing text, needs to be entered 1 Step handle FileOutputStream Packing  UTF-8 Is Code 
          OutputStreamWriter osw = new OutputStreamWriter(fos, "UTF-8");
          // write 
          osw.write(et.getText().toString());
          osw.flush();
          fos.flush();
          osw.close();
          fos.close();
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    });  

    findViewById(R.id.read).setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        try {
          FileInputStream fis = openFileInput(filename);
          // When character set encoding is specified for both input and output, scrambling will not occur 
          InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
          // Get the available length of the file, build 1 Array of characters 
          char[] input = new char[fis.available()];
          isr.read(input);
          isr.close();
          fis.close();
          String readed = new String(input);
          show.setText(readed);
        } catch (FileNotFoundException e) {
          e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    });      
  }  
}

data/data/packagename/files/test is the file we wrote.

SD Storage (External Storage)
The mnt/sdcard directory is the mount point of the SD card (only one point).
storage/sdcard: True directory for SD card operations.

1. File Download
In the development of Android, it is sometimes necessary to download some resources from the Internet for users to use. Android API has provided many directly available classes for everyone to use. 1 General file download needs three steps:
1. Create an HttpURLConnection object


//  Establish 1 individual URL Object that contains 1 individual IP Address, urlStr Refers to a network IP address  
url = new URL(urlStr); 
//  adopt URL Object to create 1 individual HttpURLConnection object 
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();

2. Obtain an InputStream object


InputStream input = urlConn.getInputStream();

3. Set up access rights to the network


// stay AndroidManifest.xml Add permission information to profile  
<uses-permission android:name="android.permission.INTERNET"/>

2. Access and write to the SD card
1. Determine if an SD card is inserted on the phone and the application has read and write permissions


Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);

2. Get the directory of the current SD card


Environment.getExternalStorageDirectory();

3. Privileges must also be set in the configuration file before accessing the SD card in order to access the SD card


<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Below is an encapsulation class that is often used for SD operations. If you need to operate on the SD card in the future, you can use it directly.


public class FileUtils {
  private String SDPATH;
  public String getSDPATH(){
    return SDPATH;
  }
  // Constructor, get SD Card directory, the directory name from this line of functions is actually called "/SDCARD"
  public FileUtils() {
    SDPATH = Environment.getExternalStorageDirectory() +"/";
  }
  // stay SD Create Files on Card 
  public File createSDFile(String fileName) throws IOException{
    File file = new File(SDPATH + fileName);
    file.createNewFile();
    return file;
  }
  // stay SD Create directory on card 
  public File createSDDir(String dirName){
    File dir = new File(SDPATH + dirName);
    dir.mkdir();
    return dir;
  }
  // judge SD Does the folder on the card exist 
  public boolean isFileExist(String fileName){
    File file = new File(SDPATH + fileName);
    return file.exists();
  }

  // take 1 individual InputStream The data inside is written to SD Card 
  // take input write to path In this directory fileName On file 
  public File write2SDFromInput(String path, String fileName, InputStream input){
    File file = null; 
    OutputStream output = null; 
    try{ 
      createSDDir(path); 
      file = createSDFile(path + fileName); 
      //FileInputStream Is to read data, FileOutputStream Is to write data to file On this file 
      output = new FileOutputStream(file); 
      byte buffer [] = new byte[4 * 1024]; 
      while((input.read(buffer)) != -1){ 
        output.write(buffer); 
      } 
      output.flush(); 
    } 
    catch(Exception e){ 
      e.printStackTrace(); 
    } 
    finally{ 
      try{ 
        output.close(); 
      } 
      catch(Exception e){ 
        e.printStackTrace(); 
      } 
    } 
    return file; 
  } 
}


Related articles: