简体   繁体   中英

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 . 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. Then you can use System.out to print to the console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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