user3029345
user3029345

Reputation:

Write ArrayList as a list in a text file

I'm using a getter method to return an ArrayList to my main method. I then save these lists into text files. The problem I have is in the way the output is displayed

Is there a way to save my array Lists in this way

eg:

12           
45         
56            
34            
65

rather than

[12, 45, 56, 34, 65]

I'm using a PrintStream and I'm outputting to a text file.

Regards

edit

for(Subject sub : st.getSub()){
         save.println(s.getSubject());
         save.println(s.getHomeworkMark());
         save.println(s.getExamMark());
        }

I have something liike that, but since im using a getter method, it doesnt let me loop through each record.... thos are retrieving from arrayLists, but when I output, it outputs as a whole rather than individuals

Upvotes: 1

Views: 1209

Answers (3)

user3029345
user3029345

Reputation:

Solved this by making a temporary variable....

Upvotes: 0

Bohemian
Bohemian

Reputation: 424973

You can do it in one line if you want:

List<Integer> list; // assuming this

printStream.print(list.toString().replaceAll("^.|.$", "").replace(", ", "\n"));

Upvotes: 1

ViRALiC
ViRALiC

Reputation: 1549

Have you tried using PrintStream's println() method?

public static void main(String[] args) {

    // Making an ArrayList
    ArrayList yourArrayHere = new ArrayList();

    // Adding your numbers
    yourArrayHere.add(12);
    yourArrayHere.add(45);
    yourArrayHere.add(56);
    yourArrayHere.add(34);
    yourArrayHere.add(65);

    // Creating a PrintStream object
    PrintStream ps = null;

    try {
        ps = new PrintStream("C:\\yourFile.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

    //Going through each object and writing it to file
    for (int i = 0; i < yourArrayHere.size(); i++) {
        ps.println(yourArrayHere.get(i));

    }

}

If that doesn't help, please share your code by editing your question so I may have a closer look.

My result in yourFile.txt, located in C:

12
45
56
34
65

Upvotes: 1

Related Questions