Java 如何在android上创建和/或附加到文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18100485/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 22:23:40  来源:igfitidea点击:

How to create and/or append to a file on android?

javaandroidfilefile-iofilewriter

提问by Arsen Zahray

Here's what I'm doing:

这是我在做什么:

    static void writeToFile(String text) {
    try {
        synchronized (fileLock) {
            File external = Environment.getExternalStorageDirectory();
            String sdcardPath = external.getPath();
            FileWriter filewriter = new FileWriter(sdcardPath
                    + "/Documents/myfile.txt", true);
            BufferedWriter out = new BufferedWriter(filewriter);

            out.write(text);

            out.close();
            filewriter.close();
        }
    } catch (Exception e) {
        android.util.Log.d("failed to save file", e.toString());
    }
}

On open file I get following exception:

在打开文件时,我收到以下异常:

java.io.FileNotFoundException: /mnt/sdcard/Documents/myfile.txt: 
    open failed: ENOENT (No such file or directory)
  1. The directory /mnt/sdcard/Documents/exists according to Root Browres
  2. The application manifest does contain <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  3. myfile.txtdoes not exist, I want it created or appended
  1. 该目录/mnt/sdcard/Documents/根据 Root Browres 存在
  2. 应用程序清单确实包含 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  3. myfile.txt不存在,我想创建或附加它

How do I create or append to a file on android?

如何在 android 上创建或附加到文件?

UPDATEHere is my AndroidManifest.xml:

更新这是我的 AndroidManifest.xml:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.mytest"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/title_activity_main" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

回答by Brtle

You can try something like that:

你可以尝试这样的事情:

static void writeToFile(String text) {
    try {
        synchronized (fileLock) {
            File external = Environment.getExternalStorageDirectory();
            String sdcardPath = external.getPath();
            File file = new File(sdcardPath + "/Documents/myfile.txt");
            file.createNewFile();
            FileWriter filewriter = new FileWriter(file);
            BufferedWriter out = new BufferedWriter(filewriter);

            out.write(text);

            out.close();
            filewriter.close();
        }
    } catch (Exception e) {
        android.util.Log.d("failed to save file", e.toString());
    }
}

回答by Prakhar

first you have to create the file then append to it this is the code to create the file

首先你必须创建文件然后附加到它这是创建文件的代码

    sFileName = "Android.txt";
    File root=Environment.getExternalStorageDirectory();

    File textfile = new File(root, sFileName);
    textfile.createNewFile();

Permission:

允许:

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

回答by M.Salomaa

Try this:

尝试这个:

        File storagePath = new File(getExternalCacheDir() + "/dirname/");
        storagePath.mkdirs();
        File myFile = new File(storagePath, fileName);
        OutputStream out = new BufferedOutputStream(new FileOutputStream(
                myFile));
        try {

            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }

        } finally {
            try {
                out.close();

            } catch (IOException e) {

            }
            try {
                inputStream.close();
            } catch (IOException e) {

            }
        }

回答by Nirmal

Use like this:

像这样使用:

   File root = android.os.Environment.getExternalStorageDirectory(); 


   // See http://stackoverflow.com/questions/3551821/android-write-to-sd-card-folder

   File dir = new File (root.getAbsolutePath() + "/download");
   dir.mkdirs();
   File file = new File(dir, "myData.txt");

   try {
       FileOutputStream f = new FileOutputStream(file);
       PrintWriter pw = new PrintWriter(f);
       pw.println("Hi , How are you");
       pw.println("Hello");
       pw.flush();
       pw.close();
       f.close();
   } catch (FileNotFoundException e) {
       e.printStackTrace();
       Log.i(TAG, "******* File not found. Did you add a WRITE_EXTERNAL_STORAGE permission to the   manifest?");
   } catch (IOException e) {
       e.printStackTrace();
   }   


OR:

或者:

     File direct = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/");

     File file = new File(Environment.getExternalStorageDirectory() + "/MyAppFolder/myFile.txt");        
     if(!direct.exists())
     {
         direct.mkdir();
     }        

     if (!file.exists()) {
             try {
                 file.createNewFile();
                 FileOutputStream f = new FileOutputStream(file);
                 PrintWriter pw = new PrintWriter(f);
                 pw.println("Hi , How are you");
                 pw.println("Hello");
                 pw.flush();
                 pw.close();
                 f.close();

             } catch (IOException e) {
                 e.printStackTrace();
             }}

Hope this will help you.

希望这会帮助你。