简体   繁体   English

Java:将文本文件输出到控制台

[英]Java: Outputting text file to Console

I'm attempting to output a text file to the console with Java.我正在尝试使用 Java 将文本文件输出到控制台。 I was wondering what is the most efficient way of doing so?我想知道这样做的最有效方法是什么?

I've researched several methods however, it's difficult to discern which is the least performance impacted solution.然而,我研究了几种方法,很难辨别哪个是对性能影响最小的解决方案。

Outputting a text file to the console would involve reading in each line in the file, then writing it to the console.将文本文件输出到控制台将涉及读取文件中的每一行,然后将其写入控制台。

Is it better to use:是否更好地使用:

  1. Buffered Reader with a FileReader, reading in lines and doing a bunch of system.out.println calls?带有 FileReader 的缓冲 Reader,按行读取并执行一堆 system.out.println 调用?

     BufferedReader in = new BufferedReader(new FileReader("C:\\\\logs\\\\")); while (in.readLine() != null) { System.out.println(blah blah blah); } in.close();
  2. Scanner reading each line in the file and doing system.print calls?扫描仪读取文件中的每一行并执行 system.print 调用?

     while (scanner.hasNextLine()) { System.out.println(blah blah blah); }

Thanks.谢谢。

If all you want to do is print the contents of a file (and don't want to print the next int/double/etc.) to the console then a BufferedReader is fine.如果您只想将文件的内容(并且不想打印下一个 int/double/etc.)打印到控制台,那么BufferedReader就可以了。

Your code as it is won't produce the result you're after, though.但是,您的代码不会产生您想要的结果。 Try this instead:试试这个:

BufferedReader in = new BufferedReader(new FileReader("C:\\logs\\log001.txt"));
String line = in.readLine();
while(line != null)
{
  System.out.println(line);
  line = in.readLine();
}
in.close();

I wouldn't get too hung up about it, though because it's more likely that the main bottleneck will be the ability of your console to print the information that Java is sending it.我不会太在意它,因为主要瓶颈更有可能是您的控制台打印 Java 发送它的信息的能力。

If you're not interested in the character based data the text file is containing, just stream it "raw" as bytes.如果您对文本文件包含的基于字符的数据不感兴趣,只需将其“原始”作为字节流式传输。

InputStream input = new BufferedInputStream(new FileInputStream("C:/logs.txt"));
byte[] buffer = new byte[8192];

try {
    for (int length = 0; (length = input.read(buffer)) != -1;) {
        System.out.write(buffer, 0, length);
    }
} finally {
    input.close();
}

This saves the cost of unnecessarily massaging between bytes and characters and also scanning and splitting on newlines and appending them once again.这节省了在字节和字符之间进行不必要的按摩以及扫描和拆分换行符并再次附加它们的成本。

As to the performance, you may find this article interesting.至于性能,你可能会觉得这篇文章很有趣。 According the article, a FileChannel with a 256K byte array which is read through a wrapped ByteBuffer and written directly from the byte array is the fastest way.根据文章,一个带有 256K 字节数组的FileChannel通过包装ByteBuffer读取并直接从字节数组中写入是最快的方式。

FileInputStream input = new FileInputStream("C:/logs.txt");
FileChannel channel = input.getChannel();
byte[] buffer = new byte[256 * 1024];
ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);

try {
    for (int length = 0; (length = channel.read(byteBuffer)) != -1;) {
        System.out.write(buffer, 0, length);
        byteBuffer.clear();
    }
} finally {
    input.close();
}

If it's a relatively small file, a one-line Java 7+ way to do this is:如果它是一个相对较小的文件,那么执行此操作的单行 Java 7+ 方法是:

System.out.println(new String(Files.readAllBytes(Paths.get("logs.txt"))));

See https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html for more details.有关更多详细信息,请参阅https://docs.oracle.com/javase/7/docs/api/java/nio/file/package-summary.html

Cheers!干杯!

If all you want is most efficiently dump the file contents to the console with no processing in-between, converting the data into characters and finding line breaks is unnecessary overhead.如果您想要的只是最有效地将文件内容转储到控制台而不进行中间处理,那么将数据转换为字符并查找换行符是不必要的开销。 Instead, you can just read blocks of bytes from the file and write then straight out to System.out :相反,您可以从文件中读取字节块,然后直接写入System.out

package toconsole;

import java.io.BufferedInputStream;
import java.io.FileInputStream;

public class Main {
    public static void main(String[] args) {
        BufferedInputStream bis = null;
        byte[] buffer = new byte[8192];
        int bytesRead = 0;
        try {
            bis = new BufferedInputStream(new FileInputStream(args[0]));
            while ((bytesRead = bis.read(buffer)) != -1) {
                System.out.write(buffer, /* start */ 0, /* length */ bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try { bis.close(); } catch (Exception e) { /* meh */ }
        }
    }
}

In case you haven't come across this kind of idiom before, the statement in the while condition both assigns the result of bis.read to bytesRead and then compares it to -1.如果您以前没有遇到过这种习惯用法,while 条件中的语句都将 bis.read 的结果分配给 bytesRead ,然后将其与 -1 进行比较。 So we keep reading bytes into the buffer until we are told that we're at the end of the file.所以我们不断地将字节读入缓冲区,直到我们被告知我们在文件的末尾。 And we use bytesRead in System.out.write to make sure we write only the bytes we've just read, as we can't assume all files are a multiple of 8 kB long!我们在 System.out.write 中使用 bytesRead 来确保我们只写入我们刚刚读取的字节,因为我们不能假设所有文件都是 8 kB 的倍数!

FileInputStream input = new FileInputStream("D:\\Java\\output.txt");
    FileChannel channel = input.getChannel();
    byte[] buffer = new byte[256 * 1024];
    ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); 

    try {
        for (int length = 0; (length = channel.read(byteBuffer)) != -1;) {
            System.out.write(buffer, 0, length);
            byteBuffer.clear();
        }
    } finally {
        input.close();
    }


    Path temp = Files.move 
            (Paths.get("D:\\\\Java\\\\output.txt"),  
            Paths.get("E:\\find\\output.txt")); 

            if(temp != null) 
            { 
                System.out.println("File renamed and moved successfully"); 
            } 
            else
            { 
                System.out.println("Failed to move the file"); 
            } 

}

For Java 1 1 you could use more convenient approach:对于Java 1 1,您可以使用更方便的方法:

Files.copy(Path.of("file.txt"), System.out);

Or for more faster output:或者为了更快的输出:

var out = new BufferedOutputStream(System.out);
Files.copy(Path.of("file.txt"), out);
out.flush();

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

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