2014-01-10 38 views
4

我有以下片的使用Java 7層的功能,如java.nio.file.Files和java.nio.file.Paths替代在Java java.nio.file.Files 6

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之外,還有哪些最好的替代方案?

+1

請注意,Oracle的Java SE 6已達到終止使用期限。 – Puce

+0

org.apache.commons.io可以幫助你 看看這個[鏈接] http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html –

回答

2

如果你真的不想使用的FileReader(雖然我不明白爲什麼),你可以去的FileInputStream。

語法:

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

這已經與'FileReader'的效果完全相同,但仍然存在使用當前平臺的默認編碼的問題,而不是您知道與文件相匹配的固定編碼。 –

1

你是正確的,以避免FileReader爲始終使用默認的字符編碼爲它正在運行的平臺,這可能不一樣的JSON文件的編碼。

ObjectMapper有readValue過載,可以直接從File閱讀,就沒有必要來緩衝在臨時byte[]內容:

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

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中讀取數據。

所以你可以用同樣的方法做,或者只是使用番石榴或Apache Commons IO http://commons.apache.org/io/

1

您可以按照說明讀入字節數組中的所有字節的文件,甚至在Java 6中的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"); 

我加入導致異常的檢查,並從readreadFully的變化,這是建議在原來的答案下評論。