Question

i want to ask if there is a way to store or write multiple lines of String array in a file from console. For example:

John 19 California
Justin 20 LA
Helena 10 NY

I just want to get some idea on how to do it using FileWriter or PrintWriter or anything related t this problem.

Was it helpful?

Solution

If you're using Java 7, you could use the Files.write method.

Here's an example:

public class Test {  
    public static void main(String[] args) throws IOException {
        String[] arr = {"John 19 California", 
                        "Justin 20 LA", 
                        "Helena 10 NY"};
        Path p = Files.write(new File("content.txt").toPath(), 
                             Arrays.asList(arr),
                             StandardCharsets.UTF_8);
        System.out.println("Wrote content to "+p);
    }   
}

OTHER TIPS

Yes, go through all the Strings in your array and write them to the desired file using FileWriter.

String[] strings = { "John 19 California",
    "Justin 20 LA",
    "Helena 10 NY" };
BufferedWriter bw = new BufferedWriter(new FileWriter("/your/file/path/foo.txt"));
for (String string : strings) {
    bw.write(string);
    bw.newLine();
}
bw.close();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top