我想在文件中写入数据,以便其他函数返回数据。
我可以在控制台中看到所有值,但不能在文件中看到。任何的想法?感谢
for (int dx = 1; dx <= 100; dx++) {
try {
File file = new File("file.txt");
file.createNewFile();
FileWriter write = new FileWriter(file);
String sizeX = (String.valueOf(Myclass.myFunction(a, b));
write.write(sizeX);
write.flush();
write.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Random random = new Random();
public static int myFunction(int a, int b) {
return (int) (random.myFunction(a*b);
}
答案 0 :(得分:2)
在for
循环之外创建,刷新并关闭文件,但在try/catch
块内。
try {
File file = new File("file.txt");
file.createNewFile();
FileWriter writer = new FileWriter(file);
for (int dx = 1; dx <= 100; dx++) {
String sizeX = (String.valueOf(Myclass.myFunction(a, b));
writer.write(sizeX);
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static Random random = new Random();
public static int myFunction(int a, int b){
return (int) (random.myFunction(a*b);
}
您可能希望在数字之间放置一个分隔符,以使输出更清晰,即:
writer.write(sizeX + "|");
答案 1 :(得分:0)
我认为这更像是你想要完成的事情
编辑 - 看起来有人已经打败了我!
要添加到下面的答案中,他是正确的,你不应该像我在下面写的那样打电话给循环内部。以下是对原因的一个很好的解释:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
public class test
{
private static Random randomFunction = new Random();
public static void main(String[] args) throws IOException
{
FileWriter write = null;
try
{
File file = new File("file.txt");
file.createNewFile();
write = new FileWriter(file);
for (int dx = 1; dx <= 100; dx++)
{
String sizeX = String.valueOf(myFunction(34, 43));
write.append(sizeX);
write.flush();
}
}
catch (IOException e)
{
e.printStackTrace();
throw e;
}
try
{
write.close();
}
catch (Exception x)
{
x.printStackTrace();
}
}
public static int myFunction(int a, int b)
{
return randomFunction.nextInt((a * b));
}
}