简体   繁体   中英

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

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

You can do it in one line if you want:

List<Integer> list; // assuming this

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

通过制作一个临时变量解决了这个问题。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM