【问题标题】:How to edit a file programmatically如何以编程方式编辑文件
【发布时间】:2013-09-12 20:35:29
【问题描述】:

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

谢谢。

【问题讨论】:

  • 那么,你有没有尝试过任何方法来完成这个?

标签: android file android-activity


【解决方案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" />

查看post 或阅读此tutorial

希望有用

【讨论】:

  • 谢谢 Gonzalo Solera,我正在寻找编辑它的最佳方式。谢谢。
【解决方案2】:

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

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;
}

哪个,我今天正在使用。我希望这可以帮助其他人。

再见。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-08
    相关资源
    最近更新 更多