0

嗨,我有以下用于写入文件的代码,它读取 a 和 b 文件并将数据放入 ab.xml 文件中

   String filePath1 = "/sdcard/Dictionarys/a.txt";
String filePath2 = "/sdcard/Dictionarys/b.txt";
String filePath3 = "/sdcard/Dictionarys/ab.xml";


        try {

        File file = new File(filePath3);
        file.createNewFile();

        BufferedReader br1 = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath1), UTF8), BUFFER_SIZE);

        BufferedReader br2 = new BufferedReader(new InputStreamReader(
                new FileInputStream(filePath2), UTF8), BUFFER_SIZE);
        FileOutputStream file3 = new FileOutputStream(filePath3);
        OutputStreamWriter out3 = new OutputStreamWriter(file3,UTF8);
        BufferedWriter br3 = new BufferedWriter(out3, BUFFER_SIZE);

        String sCurrentLine1, sCurrentLine2;

        while ((sCurrentLine1 = br1.readLine()) != null && ((sCurrentLine2 = br2.readLine())!=null)) {
            String s3 = sCurrentLine2.substring(sCurrentLine1.length());
            br3.write("<abcd abc=\""+sCurrentLine1+"\" def=\""+s3.trim()+"\"/> \n");
            br3.flush();
            i++;
        }
        br3.write("<data>\n");
        br3.flush();
        br3.close();
        out3.flush();
        out3.close();
        file3.close();
    } catch (Exception e) {
        e.printStackTrace();
    }

但 xml 文件未在 SDCARD 路径上创建..

4

2 回答 2

2

尝试以这种方式获取路径:

 Environment.getExternalStorageDirectory()

有时字符串路径不起作用,请确保您在清单中添加了以下权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
于 2013-02-12T10:41:09.740 回答
1

首先,您不应该对 sdcard 的路径进行硬编码,因为它可能会因手机而异。使用类似Context.getExternalFilesDir()or的方法getExternalStoragePublicDirectory(String)

其次,一些文件系统有缓冲。您应该使用该fsync方法来进行实际的写入。有关详细信息,请参阅安全保存数据

于 2013-02-12T10:45:23.710 回答