Make a txt file in internal storage in android

时光总嘲笑我的痴心妄想 提交于 2019-12-02 04:38:34
Biraj Zalavadia

Try this function.

public void wrtieFileOnInternalStorage(Context mcoContext,String sFileName, String sBody){
    File file = new File(mcoContext.getFilesDir(),"mydir");
    if(!file.exists()){
        file.mkdir();
    }

    try{
        File gpxfile = new File(file, sFileName);
        FileWriter writer = new FileWriter(gpxfile);
        writer.append(sBody);
        writer.flush();
        writer.close();

    }catch (Exception e){

    }
}

Try something like this -

public Boolean writeToSD(String text){
        Boolean write_successful = false;
         File root=null;  
            try {  
                // <span id="IL_AD8" class="IL_AD">check for</span> SDcard   
                root = Environment.getExternalStorageDirectory();  
                Log.i(TAG,"path.." +root.getAbsolutePath());  

                //check sdcard permission  
                if (root.canWrite()){  
                    File fileDir = new File(root.getAbsolutePath());  
                    fileDir.mkdirs();  

                    File file= new File(fileDir, "samplefile.txt");  
                    FileWriter filewriter = new FileWriter(file);  
                    BufferedWriter out = new BufferedWriter(filewriter);  
                    out.write(text);  
                    out.close();  
                    write_successful = true;
                }  
            } catch (IOException e) {  
                Log.e("ERROR:---", "Could not write file to SDCard" + e.getMessage());  
                write_successful = false;
            }  
        return write_successful;
    }

From here - http://www.coderzheaven.com/2012/09/06/read-write-files-sdcard-application-sandbox-android-complete-example/

In this statement:

File gpxfile = new File(file, sFileName);

file should be directory (you use .txt file here).

Also, read this. You can store you file in /data/data/<your.package.name>/ dir (trying to use /data/root/ will cause Permission denied error).

bhavesh kaila

Try this. Using this, I have created log file in SD card.

public void writeFile(String text){

    File tarjeta = Environment.getExternalStorageDirectory();
    File logFile = new File(tarjeta.getAbsolutePath()+"/", "log.txt");
    if (!logFile.exists())
    {
        try
        {
            logFile.createNewFile();
        } 
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    try
    {
        //BufferedWriter for performance, true to set append to file flag
        BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true)); 
        buf.append(text);
        buf.newLine();
        buf.close();
    }
    catch (IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!