如何将String写入桌面上现有的文本文件?

时间:2016-04-18 18:06:33

标签: java string file text

我想知道如何将String写入桌面上已有的文件。

此文本文件中已包含信息,因此我希望将其删除。

谢谢

2 个答案:

答案 0 :(得分:0)

以下代码会在不删除以前数据的情况下将一些文本写入文件。

BufferedWriter bw = null;


try
{
    bw = new BufferedWriter(new FileWriter("sample.txt",true));
    }catch(IOException  e)
    {
        System.out.println("ERROR:"+e);
        return;
    }

try
{
    bw.write("\r\ntext you want to write to the file");
    bw.close();
}catch(IOException e)
{
    System.out.println("ERROR:"+e);
}

}

现在,如果您想要删除数据,那么只需替换以下行:

bw = new BufferedWriter(new FileWriter("sample.txt",true));

以下内容:

bw = new BufferedWriter(new FileWriter("sample.txt"));

答案 1 :(得分:0)

试试此代码

PrintWriter p = new PrintWriter(new FileWriter("yourLocation.txt"));
String s = "hello world";
p.printf(s);
p.close();
相关问题