The following example shows ways how to read the contents of a file in Java. The ReadFileToString class reads the contents of a text file into a String.
public class ReadFileToString {
public static String fileToString(String fileName) {
File file = new File(fileName);
StringBuilder contents = new StringBuilder();
BufferedReader input = null;
try {
input = new BufferedReader(new FileReader(file));
String line = null;
while((line = input.readLine()) != null)
contents.append(line);
return contents.toString();
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
if(input != null) input.close();
} catch(Exception e) {
}
}
}
}
Example use:
public class Test {
public static void main(String[] args) {
String content = ReadFileToString.fileToString("C:\\MyTextFile.txt");
System.out.println(content);
}
}
Dealing with binary files it's more useful to read the file contents into a byte array:
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.File;
public class ReadFileToByteArray {
public static byte[] read(String fileName) {
InputStream is = null;
try {
File file = new File(fileName);
is = new FileInputStream(file);
long length = file.length();
byte[] bytes = new byte[(int) length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length
&& (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new RuntimeException("Could not completely read file " + file.getName());
}
return bytes;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if(is != null) {
try {
is.close();
} catch(Exception e) {
//
}
}
}
}
}
Use example:
public class Test {
public static void main(String[] args) {
byte[] content = ReadFileToByteArray.read("C:\\MyBinFile.txt");
}
}