简体   繁体   English

在 JAVA 中打印到控制台

[英]Print to console in JAVA

I have a simple question.我有一个简单的问题。 My program asks the user to type a name, range, and length to generate random numbers.我的程序要求用户键入名称、范围和长度以生成随机数。 The result will be printed into a file from the console.结果将从控制台打印到文件中。 I want to know is it possible to print to the console that the file has been printed when it's done.我想知道是否可以在控制台打印文件完成后打印出来。

Currently this is my set up to print to a file:目前这是我打印到文件的设置:

        Scanner s = new Scanner(System.in);
        System.out.println("-----------------------------------------------");
        System.out.println("Choose a name to your file: ");
        String fn = s.nextLine();
        
        System.out.println("-----------------------------------------------");
        System.out.println("Choose your range: ");
        String rn = s.nextLine();
        
        System.out.println("-----------------------------------------------");
        System.out.println("Choose your length of array: ");
        String ln = s.nextLine();
        
        System.out.println("-----------------------------------------------");
        
        int rangeToInt = Integer.parseInt(rn);
        int lengthToInt = Integer.parseInt(ln);
        
        File file = new File(fn +".txt");
        PrintStream stream = new PrintStream(file);
        //System.out.println("File Has been Printed");
        System.setOut(stream);
        
    
        
        int[] result = getRandomNumbersWithNoDuplicates(rangeToInt, lengthToInt);
        for(int i = 0; i < result.length; i++) {
            Arrays.sort(result);
            System.out.println(result[i] + " ");
            
        }
        
        System.out.println("Current Time in Millieseconds = " + System.currentTimeMillis());
        System.out.println("\nNumber of element in the array are: " + result.length + "\n");
        
    
    }// end of main
     ```

Don't call System.setOut .不要调用System.setOut When you do that, you can no longer print to the console.当你这样做时,你不能再打印到控制台。 Instead of System.out.println to write to the file, just... stream.println to write to the file.而不是System.out.println写入文件,只是... stream.println写入文件。 Then you can use System.out to print to the console.然后你可以使用System.out打印到控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM