将特定行写入文件

时间:2013-09-11 08:34:16

标签: java file-io

我正在从用户那里获取一些输入,例如姓名,年龄,电子邮件等。我用“:”分隔符连接所有这些字段

`String line = Anjan+":"+21+":"+abc@abcd.com;`

我的问题是: 如何将String行写入文件? 我重复从用户那里获取输入的过程。有人可以解释一下,在完成读取和连接输入之后,我怎样才能每次都将行写入文件?

3 个答案:

答案 0 :(得分:0)

public static void write(final String content, final String path)
    throws IOException {
    final FileOutputStream fos = new FileOutputStream(path);
    fos.write(content.getBytes());
    fos.close();
}

答案 1 :(得分:0)

尝试以下代码。您可以创建方法并将值作为参数传递。它每次都会添加新行。它不会删除现有的行(数据)

File logFile = new File( System.getProperty("user.home") + File.separator + "test.txt");
String data = "value";
if(!logFile.exists()){
    logFile.createNewFile();
}
FileWriter fstream = new FileWriter(logFile.getAbsolutePath(),true);
BufferedWriter fbw = new BufferedWriter(fstream);
fbw.write(data);
fbw.newLine();
fbw.close();

答案 2 :(得分:0)

如果您使用的是Java 7,那将非常简单,

    public void writerToPath(String content, Path path) throws IOException {
        try(BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(Files.newOutputStream(path,StandardOpenOption.CREATE, StandardOpenOption.APPEND)))){
            writer.newLine();
            writer.write(content);
    }
}

由于Writer实现AutoClosable接口,编写器和底层流将在完成时或发生异常时关闭。