Java – write string to CSV file
•
Java
I tried to write data to a CSV file using Java, but when I tried to open the generated file with Excel, I received an error indicating that the file was damaged When Notepad opened the file, its format was correct, so I don't know what the problem is I am using the filewriter class to output data to a file
FileWriter writer = new FileWriter("test.csv"); writer.append("ID"); writer.append(','); writer.append("name"); writer.append(','); ... writer.append('\n'); writer.flush(); writer.close();
Do I need to use some libraries in Java in order to print to CSV files? I guess you can do it yourself in Java as long as you use the correct format
Appreciate help,
Shaw
Solution
According to this Microsoft documentation, an error is displayed due to the uppercase letter "Id" as the first line Change it to "Id" and work as expected
It's strange, but
Also try to minimize file access by using file objects
I tested the following code perfectly
import java.io.File; import java.io.FileNotFoundException; import java.io.PrintWriter; public class CSV { public static void main(String[]args) throws FileNotFoundException{ PrintWriter pw = new PrintWriter(new File("test.csv")); StringBuilder sb = new StringBuilder(); sb.append("id"); sb.append(','); sb.append("Name"); sb.append('\n'); sb.append("1"); sb.append(','); sb.append("Prashant Ghimire"); sb.append('\n'); pw.write(sb.toString()); pw.close(); System.out.println("done!"); } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码