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;
import java.io.IOException;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.node.ObjectNode;
public class JacksonObjectMapper {
public static void main(String[] args) throws IOException {
byte[] jsonData = Files.readAllBytes(Paths.get("employee.txt"));
ObjectMapper objectMapper = new ObjectMapper();
Employee emp = objectMapper.readValue(jsonData, Employee.class);
System.out.println("Employee Object\n"+emp);
Employee emp1 = createEmployee();
objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
StringWriter stringEmp = new StringWriter();
objectMapper.writeValue(stringEmp, emp1);
System.out.println("Employee JSON is\n"+stringEmp);
}
}
Now I have to run the the same code on Java 6 , what are the best possible alternatives other than using FileReader ?
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/.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With