This is the code I have and essentially I want to write this into a csv
file:
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();
I want the output to be in this format, I'm getting an output where the second and third-row are all over the place :
Course Name Age
math john 7
english bob 9
CodePudding user response:
Try to remove the insertion of a newline after each write and use one loop, I will assume the three lists have the same size
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();
, or use in one-line
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();
CodePudding user response:
As best as I can tell from your question, you can do it like this. It writes to the file and to the console.
Some data
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";
- This uses try-with-resources to open and close the writer.
- Process the lists in a single loop
- put the values in an array for joining with
String.join
- and use
System.printf
to format them to the console.
- put the values in an array for joining with
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();
}
CodePudding user response:
I think use MessageFormat.format()
method(it's in java.text package) is a good solution.This is a example:
@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();
}
}
Can get:
course0,name0,1
course1,name1,2