I have the following piece of code that uses the java 7 features like java.nio.file.Files and java.nio.file.Paths
import java.io.File;
impor
Alternative are classes from java.io or Apache Commons IO, also Guava IO can help.
Guava is most modern, so I think it is the best solution for you.
Read more: Guava's I/O package utilities, explained.
You can read all bytes of a file into byte array even in Java 6 as described in an answer to a related question:
import java.io.RandomAccessFile;
import java.io.IOException;
RandomAccessFile f = new RandomAccessFile(fileName, "r");
if (f.length() > Integer.MAX_VALUE)
throw new IOException("File is too large");
byte[] b = new byte[(int)f.length()];
f.readFully(b);
if (f.getFilePointer() != f.length())
throw new IOException("File length changed while reading");
I added the checks leading to exceptions and the change from read
to readFully
, which was proposed in comments under the original answer.
If you really don't want to use FileReader(Though I didn't understand why) you can go for FileInputStream.
Syntax:
InputStream inputStream = new FileInputStream(Path of your file);
Reader reader = new InputStreamReader(inputStream);
You are right to avoid FileReader
as that always uses the default character encoding for the platform it is running on, which may not be the same as the encoding of the JSON file.
ObjectMapper has an overload of readValue
that can read directly from a File
, there's no need to buffer the content in a temporary byte[]
:
Employee emp = objectMapper.readValue(new File("employee.txt"), Employee.class);
In Files
class source you can see that in readAllBytes
method bytes are read from InputStream.
public static byte[] readAllBytes(Path path) throws IOException {
long size = size(path);
if (size > (long)Integer.MAX_VALUE)
throw new OutOfMemoryError("Required array size too large");
try (InputStream in = newInputStream(path)) {
return read(in, (int)size);
}
}
return read(in, (int)size)
- here it uses buffer to read data from InputStream.
So you can do it in the same way or just use Guava or Apache Commons IO http://commons.apache.org/io/.