您好我有3个班级,第二个班级是计算,第3个是我将前2个班级的数据保存到文本文件的地方。 我试图重用我的方法,使用FileWriter和BufferedWriter将第一和第二类的计算值写入文本文件。
所以我有这样的事情:
1)头等做计算
2)然后使用第3类writeDetected将其保存在文本文件中
3)第二课做计算
4)然后使用writeDetected
除非我想保存我在二等课程中完成的计算,否则一切正常。文本文件中的内容包含先前(第一类计算)+第二类计算。我想要的是一个具有第一类计算的文件和另一个具有第二类计算的文件。关于我应该怎么做的任何想法?
只是为了说明这一点:
它应该看起来像这样
1级{1,2,3,4}
2级{5,6,7,8}
我现在所拥有的是
1级{1,2,3,4}
第2类{1,2,3,4,5,6,7,8}
这是我的代码:
public void writeDetected(){
Scanner getFileName = new Scanner(System.in);
//Enter file name here for first class then after calculation of
// 2nd class enter another file name
String getInp = getFileName.nextLine();
try{
FileWriter theFile = new FileWriter(getInp);
BufferedWriter readBuf = new BufferedWriter (theFile);
String convDoubleToString;
for (Double getVal: detected){
convDoubleToString = getVal.toString();
readBuf.write(convDoubleToString);
readBuf.newLine();
}
readBuf.close();
}
catch (IOException e){
System.out.println(e);
}
}
答案 0 :(得分:1)
试试这个,
将path
从calling method as Argument
发送到Parameters of the called
method
,这样您就可以将文件内容写入您想要的任何文件(Here
被调用的方法将是writeMyFile(String path)
)
例如:
public void writeMyFile(String path){
Scanner scan = new Scanner(System.in);
File f = new File(path);
FileWriter fr = new FileWriter(f);
BufferedWriter br = new BufferedWriter(fr);
while(true){ // its a continuos loop, so better handle it the way u want it
br.write(new Scanner(System.in).nextLine());
}
}
答案 1 :(得分:0)
我会在方法中添加一个字符串输入变量,并传入要写入的文件名。那或者你可以创建文件对象并将它们作为输入参数传递。我自己使用了一个字符串,只是传入了文件名来写入。