3 回答

TA貢獻1811條經(jīng)驗 獲得超6個贊
我將分兩步解決這個問題:首先,閱讀標(biāo)題,然后閱讀其余的行:
static String[] headers(String path) throws IOException {
try (BufferedReader br = new BufferedReader(new FileReader(path))) {
return br.readLine().split(",");
}
}
現(xiàn)在,您可以使用上述方法如下:
String path = "sample.csv";
// Read headers
String[] headers = headers(path);
List<Map<String, String>> result = null;
// Read data
try (Stream<String> stream = Files.lines(Paths.get(path))) {
result = stream
.skip(1) // skip headers
.map(line -> line.split(","))
.map(data -> {
Map<String, String> map = new HashMap<>();
for (int i = 0; i < data.length; i++) {
map.put(headers[i], data[i]);
}
return map;
})
.collect(Collectors.toList());
}
您可以for在第二個map操作中更改循環(huán):
try (Stream<String> stream = Files.lines(Paths.get(path))) {
result = stream
.skip(1) // skip headers
.map(line -> line.split(","))
.map(data -> IntStream.range(0, data.length)
.boxed()
.collect(Collectors.toMap(i -> headers[i], i -> data[i])))
.collect(Collectors.toList());
}
編輯:如果不是收集到列表,而是要對從每一行讀取的地圖執(zhí)行操作,您可以按如下方式進行:
try (Stream<String> stream = Files.lines(Paths.get(path))) {
stream
.skip(1) // skip headers
.map(line -> line.split(","))
.map(data -> IntStream.range(0, data.length)
.boxed()
.collect(Collectors.toMap(i -> headers[i], i -> data[i])))
.forEach(System.out::println);
}
(這里的動作是打印每張地圖)。
這個版本可以改進,即它裝箱ints的流,然后int再次拆箱以將其用作headers和data數(shù)組的索引。此外,可以通過將每個映射的創(chuàng)建提取到私有方法來提高可讀性。
注意:也許讀取文件兩次不是性能方面的最佳方法,但代碼簡單且富有表現(xiàn)力。除此之外,null處理、數(shù)據(jù)轉(zhuǎn)換(即到數(shù)字或日期等)和邊界情況(即沒有標(biāo)題、沒有數(shù)據(jù)行或數(shù)據(jù)數(shù)組的不同長度等)留給讀者作為練習(xí);)

TA貢獻1772條經(jīng)驗 獲得超5個贊
我認為這就是你想要做的
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class App {
public static void main(String[] args) throws JsonProcessingException, IOException {
Stream<String> stream = Files.lines(Paths.get("src/main/resources/test1.csv"));
List<Map<String, Object>> readall = stream.map(l -> {
Map<String, Object> map = new HashMap<String, Object>();
String[] values = l.split(",");
map.put("name", values[0]);
map.put("age", values[1]);
return map;
}).collect(Collectors.toList());
ObjectMapper mapperObj = new ObjectMapper();
String jsonResp = mapperObj.writeValueAsString(readall);
System.out.println(jsonResp);
}
}
與 Java -8 Streams 一起使用,帶有標(biāo)頭,并使用 jackson 將其轉(zhuǎn)換為 json。使用過的 CSV
abc,20
bbc,30

TA貢獻1890條經(jīng)驗 獲得超9個贊
很簡單,不要把它轉(zhuǎn)換成字符串列表。將其轉(zhuǎn)換為 HashMap 列表,然后使用 org.json 庫將其轉(zhuǎn)換為 json 。使用 jackson 將 CSV 轉(zhuǎn)換為 Hashmap
讓輸入流為
InputStream stream = new FileInputStream(new File("filename.csv"));
示例:將 CSV 轉(zhuǎn)換為 HashMap
public List<Map<String, Object>> read(InputStream stream) throws JsonProcessingException, IOException {
List<Map<String, Object>> response = new LinkedList<Map<String, Object>>();
CsvMapper mapper = new CsvMapper();
CsvSchema schema = CsvSchema.emptySchema().withHeader();
MappingIterator<Map<String, String>> iterator = mapper.reader(Map.class).with(schema).readValues(stream);
while (iterator.hasNext())
{
response.add(Collections.<String, Object>unmodifiableMap(iterator.next()));
}
return response;
}
將地圖列表轉(zhuǎn)換為 Json
JSONArray jsonArray = new JSONArray(response);
System.out.println(jsonArray.toString());
添加回答
舉報