【问题标题】:Append a string at the first line of file在文件的第一行附加一个字符串
【发布时间】:2015-12-29 07:24:39
【问题描述】:

我使用代码将字符串插入到文件中。但是,该代码仅支持在文件的最后一行插入。你能帮我把它改成在android的第一行字符串写一个字符串吗?这些字符串由 line.separator 分隔

例如: 文件中的当前字符串

aaa
bbb
ccc

如果新字符串是“111”,请将其插入

111
aaa
bbb
ccc

这是我的代码

private void writeTextFile(String filecontent)
{           
        String filepath = Environment.getExternalStorageDirectory().getPath();
        String filename=filepath+"/" +  "/" + "filentxt.txt"    ;   
        FileOutputStream fop = null;
        File file = null;

        try {
            file =new File(filename);
            fop=new FileOutputStream(file,true);
            // if file doesn't exists, then create it
            if (!file.exists()) {
                file.createNewFile();
            }
            filecontent=filecontent+ System.getProperty ("line.separator");
            // get the content in bytes
            byte[] contentInBytes = filecontent.getBytes();
            fop.write(contentInBytes);
            fop.flush();
            fop.close();

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

【问题讨论】:

标签: android file fileoutputstream android-file


【解决方案1】:

使用RandomAccessFile 在文件开头写入

String filepath = Environment.getExternalStorageDirectory().getPath();
String filename=filepath+"/" +  "/" + "filentxt.txt"    ;   
RandomAccessFile f = new RandomAccessFile(new File(filename), "rw");
f.seek(0); // to the beginning
f.write("111".getBytes());
f.close();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-07
    • 1970-01-01
    • 1970-01-01
    • 2017-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多