How to save parsed text file in internal/external storage in android

后端 未结 3 1345
余生分开走
余生分开走 2021-01-13 16:51

Currently I am working in project where I need to parse a remote text file and store it in local storage (internal/external). I am able to parse the text file but unable to

相关标签:
3条回答
  • 2021-01-13 17:14

    First thing, your AndroidManifest.xml file is correct. So no need to correct that. Though I would recommend organizing your permissions in one place.

    Writing File to Internal Storage

    FileOutputStream fOut = openFileOutput("myinternalfile.txt",MODE_WORLD_READABLE);
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    
    //---write the contents to the file---
    osw.write(strFileData);
    osw.flush();
    osw.close();
    

    Writing File to External SD Card

    //This will get the SD Card directory and create a folder named MyFiles in it.
    File sdCard = Environment.getExternalStorageDirectory();
    File directory = new File (sdCard.getAbsolutePath() + "/MyFiles");
    directory.mkdirs();
    
    //Now create the file in the above directory and write the contents into it
    File file = new File(directory, "mysdfile.txt");
    FileOutputStream fOut = new FileOutputStream(file);
    OutputStreamWriter osw = new OutputStreamWriter(fOut);
    osw.write(strFileData);
    osw.flush();
    osw.close();
    

    Note: If running on an emulator, ensure that you have enabled SD Card support in the AVD properties and allocated it appropriate space.

    0 讨论(0)
  • 2021-01-13 17:33

    Replace this lines

    File myFile = new File("sdcard/mysdfile.txt");
    if(!myFile.exists()){
      myFile.mkdirs();
     }
    myFile = new File("sdcard/mysdfile.txt");
    

    with

    //Saving the parsed data.........

    File myFile = new File(Environment.getExternalStorageDirectory()+"/mysdfile.txt");
    myFile.createNewFile();
    
    0 讨论(0)
  • 2021-01-13 17:33
    File myFile = new File("sdcard/mysdfile.txt");
    

    Should be changed to

    File myFile = new File("/mnt/sdcard/mysdfile.txt");
    
    0 讨论(0)
提交回复
热议问题