Home > Net >  Print to console in JAVA
Print to console in JAVA

Time:04-27

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
     ```

CodePudding user response:

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.

  • Related