這是我擁有的代碼,本質上我想將其寫入csv檔案:
ArrayList <String> course = new ArrayList<>();
ArrayList <String> name = new ArrayList<>();
ArrayList <Integer> age = new ArrayList<>();
File file = new File("jj.csv");
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Course,Name,Age");
bw.newLine();
for (int i = 0; i < course.size(); i ) {
bw.write(course.get(i));
bw.newLine();
}
for (int i = 0; i < name.size(); i ) {
bw.write("," name.get(i));
bw.newLine();
}
for (int i = 0; i < age.size(); i ) {
bw.write("," age.get(i));
bw.newLine();
}
bw.close();
fw.close();
我希望輸出采用這種格式,我得到一個輸出,其中第二行和第三行到處都是:
Course Name Age
math john 7
english bob 9
uj5u.com熱心網友回復:
嘗試在每次寫入后洗掉換行符的插入并使用一個回圈,我將假設三個串列具有相同的大小
for(int i=0;i<course.size();i ) {
bw.write(course.get(i));
bw.write("," name.get(i));
bw.write("," age.get(i));
bw.newLine();
}
bw.close();
fw.close();
, 或單行使用
for(int i=0;i<course.size();i ) {
bw.write(course.get(i) "," name.get(i) "," age.get(i));
bw.newLine();
}
bw.close();
fw.close();
uj5u.com熱心網友回復:
盡我所能從您的問題中得知,您可以這樣做。它寫入檔案和控制臺。
一些資料
List<String> course = List.of("math", "english", "chemistry");
List<String> name = List.of("John", "Mary", "James");
List<Integer> age = List.of(19, 20, 20);
// file destination and format string
File file = new File("jj.csv");
String format = "%-10s %-8s %-4s%n";
- 這使用 try-with-resources 來打開和關閉 writer。
- 在單個回圈中處理串列
- 將值放入陣列中以加入
String.join - 并用于
System.printf將它們格式化到控制臺。
- 將值放入陣列中以加入
try (BufferedWriter bw =
new BufferedWriter(new FileWriter(file))) {
bw.write("Course,Name,Age");
System.out.printf(format, "Course", "Name",
"Age");
for (int i = 0; i < course.size(); i ) {
String s =
String.join(",", new String[] { course.get(i),
name.get(i), age.get(i) "" });
System.out.printf(format, course.get(i),
name.get(i), age.get(i));
bw.write("," s);
}
} catch (Exception e) {
e.printStackTrace();
}
uj5u.com熱心網友回復:
我認為使用MessageFormat.format()方法(它在 java.text 包中)是一個很好的解決方案。這是一個例子:
@Test
public void test05(){
final String formatTemplate = "{0},{1},{2}";
List<String> course = Arrays.asList("course0","course1");
List <String> name = Arrays.asList("name0","name1");
List <Integer> age = Arrays.asList(1,2);
final int size = course.size();
for (int i = 0; i < size; i ) {
final String lineString = MessageFormat.format(formatTemplate, course.get(i), name.get(i), age.get(i));
System.out.println(lineString);
//TODO: bw.write(linString);bw.newLine();
}
}
可以得到:
course0,name0,1
course1,name1,2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/477425.html
