我有下面一段使用 java 7 功能的代码,例如java.nio.file.Files 和 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);
}
}
现在我必须在 Java 6 上运行相同的代码,除了使用 FileReader 之外,最好的替代方案是什么?
In Files
类源你可以看到readAllBytes
方法字节从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)
- 这里它使用缓冲区从InputStream读取数据。
所以你可以用同样的方式来做,或者只使用 Guava 或 Apache Commons IOhttp://commons.apache.org/io/.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)