替代 Java 6 中的 java.nio.file.Files

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21039579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:08:58  来源:igfitidea点击:

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

java

提问by Amit Sharad

I have the following piece of code that uses the java 7 features like java.nio.file.Files and java.nio.file.Paths

我有以下一段代码,它使用了java.nio.file.Files 和 java.nio.file.Paths等 java 7 功能

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.Hymanson.core.type.TypeReference;
import com.fasterxml.Hymanson.databind.JsonNode;
import com.fasterxml.Hymanson.databind.ObjectMapper;
import com.fasterxml.Hymanson.databind.SerializationFeature;
import com.fasterxml.Hymanson.databind.node.ObjectNode;


public class HymansonObjectMapper {

    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 ?

现在我必须在 Java 6 上运行相同的代码,除了使用 FileReader 之外,最好的替代方法是什么?

采纳答案by MariuszS

Alternative are classes from java.ioor Apache Commons IO, also Guava IOcan help.

替代方法是java.ioApache Commons IO 中的类Guava IO也可以提供帮助。

Guava is most modern, so I think it is the best solution for you.

Guava 是最现代的,所以我认为它是最适合您的解决方案。

Read more: Guava's I/O package utilities, explained.

阅读更多:解释了Guava 的 I/O 包实用程序。

回答by Helios

If you really don't want to use FileReader(Though I didn't understand why) you can go for FileInputStream.

如果你真的不想使用 FileReader(虽然我不明白为什么)你可以去 FileInputStream。

Syntax:

句法:

InputStream inputStream = new FileInputStream(Path of your file);
Reader reader = new InputStreamReader(inputStream);

回答by Ian Roberts

You are right to avoid FileReaderas 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.

您应该避免,FileReader因为它始终使用运行平台的默认字符编码,这可能与 JSON 文件的编码不同。

ObjectMapper has an overload of readValuethat can read directly from a File, there's no need to buffer the content in a temporary byte[]:

ObjectMapper 有一个readValue可以直接从 a 读取的重载,File不需要在临时 中缓冲内容byte[]

Employee emp = objectMapper.readValue(new File("employee.txt"), Employee.class);

回答by pomkine

In Filesclass source you can see that in readAllBytesmethod bytes are read from InputStream.

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)- here it uses buffer to read data from InputStream.

return read(in, (int)size)- 这里它使用缓冲区从 InputStream 读取数据。

So you can do it in the same way or just use Guava or Apache Commons IO http://commons.apache.org/io/.

所以你可以用同样的方式来做,或者只使用 Guava 或 Apache Commons IO http://commons.apache.org/io/

回答by Palec

You can read all bytes of a file into byte array even in Java 6 as described in an answer to a related question:

即使在 Java 6 中,您也可以将文件的所有字节读入字节数组,如相关问题回答中所述

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 readto readFully, which was proposed in comments under the original answer.

我添加了导致异常的检查以及从readto的更改readFully,这是在原始答案下的评论中提出的。