我需要使用Java I / O将100个整数写入文件中

时间:2015-05-05 21:54:49

标签: java

我需要使用Java I / O将100个整数写入文件中 到目前为止,这是我的代码:

package lab;
import java.util.*;
import java.io.*;

public class test {
    public static void main(String[] args) {
        Random num = new Random();

        try {
            File file = new File("E:\\Test.txt");
            if(file.exists()) {
                file.createNewFile();
        }

        PrintWriter out = new PrintWriter(new File("E:\\Test.txt"));
        for (int i = 0; i <= 9; i++){
             output.print(num.nextInt(100)+" "+num.nextInt(100) + " " +
            num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
            + num.nextInt(100) + " " + num.nextInt(100) + " " + num.nextInt(100) + " "
            + num.nextInt(100) + " " + num.nextInt(100));
            output.println();
        }
        out.close();

        Scanner input = new Scanner(file);
        while(input.hasNext()) {
            System.out.println(input.nextLine());
        }
        input.close();
        }
        catch (IOException ex) {
            System.out.println("File Already Exists!");
        }
    }
}

我需要简化“for-loop”,并能够回读文件以显示它。 有人可以帮忙吗?

3 个答案:

答案 0 :(得分:0)

首先,不要在for循环中连接Strings(创建新对象),使用StringBuilder。

使用随机数构建字符串后,将其保存为: http://www.mkyong.com/java/how-to-write-to-file-in-java-bufferedwriter-example/

答案 1 :(得分:0)

StringBuilder str = new StringBuilder();
Random rng = new Random();
for (int i = 0; i < 100; ++i)
    str.append(rng.nextInt(100) + " ");

System.out.println(str.toString());

System.out.println(str.toString());替换为您的文件流写作。

答案 2 :(得分:0)

 File file = new File("File_name.txt");
 StringBuilder str = new StringBuilder();
 try (PrintWriter output = new PrintWriter(file);) {
      for (int i = 0; i < 100; i++) {
          int num = ((int)(Math.random() * 500) + 1);    
          output.print(num);
          output.print(" ");
          str.append(num + " ");
     }
}
System.out.println(str.toString());