-1

我想做一个可以编辑文件的应用程序,比如打开一个 txt 文件,编辑它,保存并记住它的权限。我如何在活动中做到这一点?

谢谢你。

4

2 回答 2

1

您可以像这样创建它:

    try {
        final FileOutputStream fos = openFileOutput(fileName + extension, Context.MODE_PRIVATE);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }

接下来,您可以使用 FileInputStream 打开和编辑它。

您需要添加的权限:

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

请参阅该帖子或阅读本教程

希望有用

于 2013-09-09T11:12:04.080 回答
1

几天后,我有了下一个方法。

private static byte[] readFromFile(String filePath, int position, int size)
        throws IOException {

    RandomAccessFile file = new RandomAccessFile(filePath, "r");
    file.seek(position);
    byte[] bytes = new byte[size];
    file.read(bytes);
    file.close();
    return bytes;

}

private void CopyFromAssetsToStorage(Context Context, String SourceFile, String DestinationFile) throws IOException {
    InputStream IS = Context.getAssets().open(SourceFile);
    OutputStream OS = new FileOutputStream(DestinationFile);
    CopyStream(IS, OS);
    OS.flush();
    OS.close();
    IS.close();
}

private void CopyStream(InputStream Input, OutputStream Output) throws IOException {
    byte[] buffer = new byte[5120];
    int length = Input.read(buffer);
    while (length > 0) {
        Output.write(buffer, 0, length);
        length = Input.read(buffer);
    }
}

private static void writeToFile(String filePath, String data, int position) throws IOException {

    RandomAccessFile file = new RandomAccessFile(filePath, "rw");
    file.seek(position);
    file.write(data.getBytes());
    file.close();



public static String readFileAsString(String filePath) throws IOException
{
    String separator = System.getProperty("line.separator");

    BufferedReader reader = new BufferedReader(new FileReader(filePath));
    String line, results = "";
    while( ( line = reader.readLine() ) != null)
    {
        results += line + separator;
    }
    reader.close();
    return results;
}

哪个,我今天用的。我希望这可以帮助别人。

再见。

于 2013-09-18T17:08:49.840 回答