在JAVA中打印到控制台

问题描述 投票:0回答:2

我有一个简单的问题。我的程序要求用户输入名称、范围和长度来生成随机数。结果将从控制台打印到文件中。我想知道完成后是否可以在控制台上打印文件已打印的信息。

目前这是我打印到文件的设置:

        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
     ```
java file console
2个回答
3
投票

不要打电话给

System.setOut
。当您这样做时,您将无法再打印到控制台。而不是
System.out.println
写入文件,只需...
stream.println
写入文件。然后您可以使用
System.out
打印到控制台。


0
投票

rzwitserloot的回答是正确的。如今,我们有了替代方案。

java.time

不再需要使用

System.currentTimeMillis()
。被 java.time 类取代,特别是
Instant.now()
,它捕获 UTC 中的当前时刻。

在 Java 8 中,这会解析为毫秒,而在 Java 9 及更高版本中,这会在许多实现中解析为更精细的微秒级别。

Instant start = Instant.now() ;

使用

Duration
计算经过的时间。

Duration duration = Duration.between ( start , Instant.now() ) ;

java.io.IO

使用 Java 23 和 24 中的预览功能,使用新的

java.io.IO
类以更轻松地使用控制台。将用户提示作为参数传递给
IO.readln

// Gather inputs.
String fileName = IO.readln ( "Choose a name to your file: " );

String rangeInput = IO.readln ( "Specify our range:" );
int range = Integer.parseInt ( rangeInput );

String arrayInput = IO.readln ( "Specify length of array:" );
int arrayLength = Integer.parseInt ( arrayInput );

// Dump to console
IO.println ( "fileName = " + fileName );
IO.println ( "range = " + range );
IO.println ( "arrayLength = " + arrayLength );

运行时:

Choose a name to your file: Bogus
Specify our range:42
Specify length of array:7
fileName = Bogus
range = 42
arrayLength = 7

Stream

编写一些逻辑来获取不同值的数组。使用 Java 8+ 中的

Stream
功能使这变得非常简单。

int[] ints =
        ThreadLocalRandom
                .current ( )
                .ints ( 0 , range )
                .distinct ( )
                .limit ( arrayLength )
                .toArray ( );

整数 = [41, 19, 11, 40, 16, 34, 35]

NIO.2

现代 Java 提供 NIO.2 功能以简化文件处理。

我们可以通过调用

Files.write
轻松编写文本行集合。

有序集合

Java 21 及更高版本现在受益于 顺序集合,以及添加到 Java 集合框架的附加接口。请参阅斯图尔特·马克斯的演讲

SequencedCollection
List
等的超级接口。

因此,首先将我们的域数据(一组

int
原语)转换为我们的序列化数据(一个由 SequencedCollection
 对象组成的 
String
)。

SequencedCollection < String > lines =
        Arrays
                .stream ( ints )
                .mapToObj ( Integer :: toString )
                .toList ( );

写入文件。请注意 NIO.2 如何简化我们的文件工作。

Path path = Paths.get ( "/Users/basil_dot_work/" , fileName );
Path resultingPath;
try { resultingPath = Files.write ( path , lines , StandardCharsets.UTF_8 ); }
catch ( IOException e ) { throw new RuntimeException ( e ); }

示例代码

为了方便您复制粘贴,这里是整个应用程序。

package work.basil.example.console;

import java.io.IO;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.SequencedCollection;
import java.util.concurrent.ThreadLocalRandom;

public class MakeFile
{
    public static void main ( String[] args )
    {
        // Gather inputs.
        String fileName = IO.readln ( "Choose a name to your file: " );

        String rangeInput = IO.readln ( "Specify our range:" );
        int range = Integer.parseInt ( rangeInput );

        String arrayInput = IO.readln ( "Specify length of array:" );
        int arrayLength = Integer.parseInt ( arrayInput );

        // Start the stopwatch.
        Instant start = Instant.now ( );

        // Domain data.
        int[] ints =
                ThreadLocalRandom
                        .current ( )
                        .ints ( 0 , range )
                        .distinct ( )
                        .limit ( arrayLength )
                        .toArray ( );


        // Serialized data.
        SequencedCollection < String > lines =
                Arrays
                        .stream ( ints )
                        .mapToObj ( Integer :: toString )
                        .toList ( );

        // Write file
        Path path = Paths.get ( "/Users/basil_dot_work/" , fileName );
        Path resultingPath;
        try { resultingPath = Files.write ( path , lines , StandardCharsets.UTF_8 ); }
        catch ( IOException e ) { throw new RuntimeException ( e ); }

        // Dump to console
        IO.println ( "fileName = " + fileName );
        IO.println ( "range = " + range );
        IO.println ( "arrayLength = " + arrayLength );
        IO.println ( "ints = " + Arrays.toString ( ints ) );
        IO.println ( "lines.toString(): " + lines );
        IO.println ( "path: " + path );
        IO.println ( "resultingPath = " + resultingPath );
        IO.println ( "Elapsed: " + Duration.between ( start , Instant.now ( ) ) );

    }
}

在 macOS Sonoma 14.7.1 上配备 M1 Pro Apple Silicon 的 MacBook Pro 上运行 Java 23.0.1 时。

Choose a name to your file: Bogus
Specify our range:42
Specify length of array:7
fileName = Bogus
range = 42
arrayLength = 7
ints = [40, 37, 8, 4, 18, 41, 24]
lines.toString(): [40, 37, 8, 4, 18, 41, 24]
path: /Users/basil_dot_work/Bogus
resultingPath = /Users/basil_dot_work/Bogus
Elapsed: PT0.002611S
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.