我正在工作一个小程序,我可以将一个列表写入 json 文件,所以我创建了 Dealer 类的两个实例,然后将其添加到“dealerList”中。
我试图写入名为“Dealer.json”的 json 文件,所以我从名为“dealerList”的列表中读取对象,然后将其写入 json 文件。
public class Main {
private static List<Dealer> dealerList = new ArrayList<>();
public static void main(String[] args) {
Dealer dearler = new Dealer("Chevrolet");
dearler.addCartoDealer(new Cars("Camaro","Steve",11000));
dearler.addCartoDealer(new Cars("Coverette","Jhon",22000));
Dealer dearler1 = new Dealer("Ford");
dearler1.addCartoDealer(new Cars("Ford1","Jessie",11000));
dearler1.addCartoDealer(new Cars("Ford2","Smith",22000));
dealerList.add(dearler);
dealerList.add(dearler1);
ObjectMapper mapper = new ObjectMapper();
try(FileOutputStream newFile = new FileOutputStream("Dealer.json")){
for(Dealer dealer:dealerList){
mapper.writeValue(newFile,dealer);
}
} catch (IOException e){
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)
我得到的堆栈:
java.io.IOException: Stream Closed
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:326)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator._flushBuffer(UTF8JsonGenerator.java:2093)
at com.fasterxml.jackson.core.json.UTF8JsonGenerator.close(UTF8JsonGenerator.java:1137)
at com.fasterxml.jackson.databind.ObjectMapper._configAndWriteValue(ObjectMapper.java:3983)
at com.fasterxml.jackson.databind.ObjectMapper.writeValue(ObjectMapper.java:3245)
at com.Ayoub.Main.main(Main.java:26)
Run Code Online (Sandbox Code Playgroud)
我得到了 Stream 关闭异常
我认为杰克逊在拨打电话后会自动关闭您的流writeValue。您可以通过以下方式关闭此功能:
MessagePackFactory messagePackFactory = new MessagePackFactory();
messagePackFactory.disable(JsonGenerator.Feature.AUTO_CLOSE_TARGET);
ObjectMapper objectMapper = new ObjectMapper(messagePackFactory);
Run Code Online (Sandbox Code Playgroud)
不要忘记在某个时间点自己关闭流;-)
| 归档时间: |
|
| 查看次数: |
2071 次 |
| 最近记录: |