0

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.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
rilakkuma
  • 15
  • 4

2 Answers2

1

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);
    }   
}
MirroredFate
  • 12,396
  • 14
  • 68
  • 100
Alexis C.
  • 91,686
  • 21
  • 171
  • 177
0

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();
Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
  • this is good. how if user have to key in the details from the console and the save it in the file? is it possible to do so? – rilakkuma Apr 24 '14 at 17:28
  • @rilakkuma read the user input first, store the data in an array or in a `List`, then dump the content into a file. To resolve a problem, split it into smaller problems and solve each problem at a time. – Luiggi Mendoza Apr 24 '14 at 17:29
  • if i want to split it then i have to create another file to store the split details? – rilakkuma Apr 24 '14 at 17:32