Java - Reading in entire files at once

S1ght

Expert Member
Joined
Jan 23, 2006
Messages
3,301
Reaction score
27
Location
Berlin
Hi guys,

Just started java this year, must say I'm enjoying it so far :) for our prac this week we have a do a program where it reads in the contents of a text file where in the text file its just a lot of random letters and then eventually has <---! a message !--->. Now normally this is easy but in this file the lecturer put in 170 pages worth of random letters and although that's still easy to read in with the scanner class with nextLine() it just takes a really long time cause there are so many lines. So I've been trying to find out how to read the entire text file in at once instead of line by line, any ideas?

Thanx in advance
S1ght :)
 
yes, but it is not really advisable to do this unless you know for a fact that the file will never be enormous. reason being that to read the entire file in one go, you have to allocate enough memory for the file.

Code:
package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class FileReader {
	public static void main(final String[] args) {
		readFile("c:\\temp\\file.txt");
	}

	public static byte[] readFile(final String fileName) {
		FileInputStream in = null;
		try {
			final File file = new File(fileName);
			if (file.isFile() && file.exists()) {
				in = new FileInputStream(file);
				int read = 0, totalRead = 0;
				final int fileLength = (int) file.length();
				final byte[] fileBytes = new byte[fileLength];
				while ((read != -1) && (totalRead < fileLength)) {
					read = in.read(fileBytes, totalRead, fileLength - totalRead);
					if (read != -1) {
						totalRead += read;
					}
				}
				return fileBytes;
			}
		} catch (final FileNotFoundException e) {
			e.printStackTrace();
		} catch (final IOException e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				try {
					in.close();
				} catch (final IOException ignore) {
				}
			}
		}
		return null;
	}
}
 
Thanks for the advice guys :)

I decided to do a little more research to see what other options there are since you guys didn't recommend reading it the file in all at once. Read through some things about StringBuffers and a BufferedReader and that seemed to do that trick, took the compile time from 1 minute down to 5 seconds :)
 
BufferedReader is a step in the right direction, but if you know what you are looking for try the RandomAccessFile class. I don't have my dev machine with me right now so I can't post code.
 
Top
Sign up to the MyBroadband newsletter
X