使用 Java 将字符串数组写入文件 - 单独的行 [英] Writing a string array to file using Java - separate lines

查看:53
本文介绍了使用 Java 将字符串数组写入文件 - 单独的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序,该程序以字符串数组(来自用户输入)的形式将观察集写入文件.我可以将观察写入 .txt 文件,然后在不删除以前数据的情况下添加新观察,但我的所有数据都在同一行上.我需要将每组观察值放在单独的行上.此外,我需要能够稍后访问该文件并从中读取.

I'm writing a program that writes sets of observations in the form of a String array (from User input) to file. I am able to write an observation to a .txt file and then add a new observation without removing the previous data, but all my data is on the same line. I need each set of observations to be on a separate line. Additionally I will need to be able to access the file later on and read from it.

我的代码目前看起来是这样的:(观察的是字符串数组)

My code currently looks like this: (observation is the string array)

for(int i = 0; i < observation.length; i++) {
    try (BufferedWriter bw = new BufferedWriter(new FileWriter("birdobservations.txt", true))) {
        String s;
        s = observation[i];
        bw.write(s);
        bw.flush();
    } catch(IOException ex) {}  
}

我的输出目前看起来像这样:CrowMOsloMay2015JayMOsloJune2012CrowMOsloMay2015RobinFBergenMay2012

My output currently looks like this: CrowMOsloMay2015JayMOsloJune2012CrowMOsloMay2015RobinFBergenMay2012

我希望它看起来像这样:

I would like it to look like this:

Crow M Oslo May2015

Jay M Oslo June2012

...等

我该怎么做?我想我需要某种循环,但我已经坚持解决这个问题有一段时间了.

How do I do this? I assume I need some kind of loop, but I've been stuck on figuring this out for a while now.

推荐答案

为什么不在 try{} 块中迭代并使用 BufferedWriter.newLine() 每次写入后?

Why not iterate within your try{} block and use BufferedWriter.newLine() after each write ?

如果您需要能够在稍后读回这些值,您需要考虑一些明确的输出格式.也许最简单的解决方案是 CSV 格式(我注意到您的输出数据有空格 - 在这种情况下,您需要使用空格以外的其他内容分隔条目)

If you need to be able to read the values back in later, you need to consider some unambiguous output format. Perhaps the simplest solution is a CSV format (I note your output data has spaces - you would need to separate your entries using something other than spaces in that case)

这篇关于使用 Java 将字符串数组写入文件 - 单独的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆