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.

1
  • you mean this? Commented Apr 24, 2014 at 17:23

2 Answers 2

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);
    }   
}
Sign up to request clarification or add additional context in comments.

Comments

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();

3 Comments

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 read the user input first, store the data in an array or in a List<String>, then dump the content into a file. To resolve a problem, split it into smaller problems and solve each problem at a time.
if i want to split it then i have to create another file to store the split details?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.