How to Input a File in Java
The Java programming language allows you to take a file as input through its standard library of classes and methods. Although Java includes a set of classes that specialize in text -- that is, files that are readable by humans -- it also includes primitives for files with arbitrary contents. These are sometimes called "binary" files. You can write Java code that takes the contents of an binary file as input for further processing.
Instructions
-
-
1
Assign the name of the file whose contents need to be read to a string within your Java program, as in the following sample code:
String myFileName = "curcuncho.txt";
-
2
Create a file input stream that has the file in question as source, as in the following sample code:
BufferedInputStream myInput = new BufferedInputStream(new FileInputStream(myFileName));
The buffered input stream reads segments of known size from the file input stream.
-
-
3
Create a memory buffer -- using the primitive "byte" Java type -- to hold each segment as it is read from the input file, as in the following sample code:
byte[] myBuffer = new byte[2048];
Replace "2048" with the number of bytes you want your application to read at a time.
-
4
Iterate over the BufferedInputStream you opened in Step 2, by reading at most 2,048 bytes at a time into the memory buffer as in the following sample code:
try {
int read;
read = myInput.read(myBuffer,0,2048);
while (read > 0) {
useReadData(myBuffer,read);
read = myInput.read(myBuffer,0,2048);
}
}
finally {
myInput.close();
}
Replace the "useReadData()" call with whatever processing your application needs to apply to the file data read into the memory buffer. The sample code reads at most 2,048 bytes at a time; the number of bytes gathered during the most recent file read is stored in variable "read." When library method "BufferedInputStream.read()" returns 0 bytes at the end of the file, the sample code closes the file.
-
1