Java 我想得到一行作为标题,其余数据追加到文件中
我想得到一行作为头,然后在文件中附加其余的数据。但我面临的问题是,当我调用函数时,它会重复保存头 预期的输出应该是 Id:标题:组Id 1:ab:2 2:fd:3 3:fwsj:3Java 我想得到一行作为标题,其余数据追加到文件中,java,file,file-handling,Java,File,File Handling,我想得到一行作为头,然后在文件中附加其余的数据。但我面临的问题是,当我调用函数时,它会重复保存头 预期的输出应该是 Id:标题:组Id 1:ab:2 2:fd:3 3:fwsj:3 public void writeOutputToFile(int id, String title, int groupId) throws IOException { OutputStream os = new FileOutputStream(new File("output_re
public void writeOutputToFile(int id, String title, int groupId) throws IOException {
OutputStream os = new FileOutputStream(new File("output_report.txt"), true);
os.write("\n Id Title Group ID \n ".getBytes());
os.write((id + " " +title + " " + groupId + "\n").getBytes());
os.close();
}
问题
它重复地放入头,因为当您调用该方法时,总是要插入头。相反,您可能希望编写一个util,为正在创建的文件输入标题,然后编写一个单独的方法来插入数据
解决方案
解决方案1)
helper util方法的外观如下所示:
// String... allows for multiple string parameters to be entered for all of your headers.
public void prepFile(File f, String... headers) {
StringBuffer buffer = new StringBuffer();
for (String header : headers) {
buffer.append(header + "\t");
}
OutputStream os = new FileOutputStream(f, true);
os.write(buffer.toString().getBytes());
os.close();
}
准备好文件后,可以对所有数据使用WriteOutput文件方法
编辑
解决方案2)
如果您打算为此制作一个独立的类,我建议您这样设置:
import java.io.*;
public class OutputFile {
private File file;
private String[] headers;
private boolean existed;
public OutputFile(File f, String... headers) {
this.file = f;
this.headers = headers;
init();
}
private void init() {
existed = file.exists();
// If the file didn't exist, then you want to create it.
if (!existed) {
try {
file.createNewFile();
// Afterwards, you can then write your headers to it.
if (headers != null) {
writeData(headers);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void writeData(int id, String title, int groupId) {
writeData("" + id, title, "" + groupId);
}
public void writeData(String... strings) {
StringBuffer buffer = new StringBuffer();
for (String s : strings) {
buffer.append(s + "\t");
}
buffer.append("\n");
writeData(buffer.toString());
}
public void writeData(String data) {
OutputStream os = null;
try {
os = new FileOutputStream(file, true);
os.write(data.getBytes());
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
好的,在你的方法中,你将头写入文件,所以很明显,无论何时调用它,它们都会被写入 您可以将其分为两种方法—一种写入标题(仅调用一次),另一种写入数据(每行调用一次)。
或者,在写入标题一次后,在方法中使用某种循环将每一行写入文件。先生,请按照我的方法更新您的答案。我无法实现此功能。我添加了一个示例,说明如何围绕此设计构建类。