如何以编程方式编辑文件

时间:2013-09-09 11:05:02

标签: android file android-activity

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

谢谢。

2 个答案:

答案 0 :(得分: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

希望它有用

答案 1 :(得分: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;
}

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

很快见到你。