如何正确打印出创建文件的内容?

时间:2018-04-22 23:58:02

标签: java file

我正在创建一个程序来创建一个新文件,并在其中放置100个随机整数,从0到100。输入数字后,我需要按递增顺序返回文件的内容。但是现在我似乎无法弄清楚什么原因导致没有打印出来。

    public static void main(String[] args) throws IOException {
    try {
        File f = new File("integerFile.txt");
        if (!f.exists()) {
            f.createNewFile();
        }
        int arr[] = new int[100];
        FileWriter fw = new FileWriter(f, true);
        PrintWriter pw = new PrintWriter(fw);
        for (int i = 0; i < 100; i++) {
            arr[i] = (int) ((Math.random() * 100));
        }
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = 0; j < arr.length - i - 1; j++) {
                int temp;
                if (arr[j] > arr[j + 1]) {
                    temp = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = temp;
                }
            }
        }
        for (int i = 0; i < arr.length; i++) {
            pw.print(arr[i] + " ");
        }
        pw.close();
    } catch (
    IOException ioe)
    {
        System.out.println("No file exits");
        ioe.printStackTrace();
    }

1 个答案:

答案 0 :(得分:0)

它不打印,因为pw.print()正在写入文件&#34; integerFile.txt&#34;。要打印到控制台,您必须使用System.out.println(arr[i]);

但是,您需要创建一个新循环来执行此操作。否则你不会写信给你的文件。

如果您想在写入文件后阅读该文件,然后打印出该文件的内容,请尝试以下操作:

FileReader myFileReader;
myFileReader = new FileReader(//Your file name);
BufferedReader b; 
b = new BufferedReader(myFileReader);//Read the file
//Write a loop to print out the contents
String line;
line = b.readLine();
while (line != null)
{
    System.out.println(line);
    line = b.readLine();
}
b.close();
相关问题