user459811
user459811

Reputation: 2894

Java: Outputting text file to Console

I'm attempting to output a text file to the console with 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?

    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?

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

Thanks.

Upvotes: 5

Views: 46478

Answers (6)

Volodya Lombrozo
Volodya Lombrozo

Reputation: 3454

For Java 11 you could use more convenient approach:

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();

Upvotes: 0

Harshitha Aravind
Harshitha Aravind

Reputation: 1

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"); 
            } 

}

Upvotes: 0

Ari
Ari

Reputation: 81

If it's a relatively small file, a one-line Java 7+ way to do this is:

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.

Cheers!

Upvotes: 4

BalusC
BalusC

Reputation: 1108722

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.

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();
}

Upvotes: 4

Zarkonnen
Zarkonnen

Reputation: 22478

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:

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. 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!

Upvotes: 2

Catchwa
Catchwa

Reputation: 5855

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.

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.

Upvotes: 5

Related Questions