Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternative to java.nio.file.Files in Java 6

Tags:

java

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 ?

like image 581
Amit Sharad Avatar asked Jan 10 '14 08:01

Amit Sharad


Video Answer


2 Answers

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/.

like image 175
pomkine Avatar answered Sep 20 '22 21:09

pomkine


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.

like image 43
MariuszS Avatar answered Sep 19 '22 21:09

MariuszS