user3929251
user3929251

Reputation: 173

Java IO: How to go to the next line after a certain amount of numbers have been written?

Hi I want to write an array to a file I can do this except I want to write the first 50 objects of the array on first line then move to the next line and write another 50 numbers and then the next line and so on.

at the moment I have this:

if (pause.save) {
        Formatter f;
        FileWriter fw;
        PrintWriter pw = null;

        File f2 = new File("docs/save.txt");

        FileReader r;
        BufferedReader r1;
        try{


            //f = new Formatter("docs/save.txt");

            f2.createNewFile();

            fw = new FileWriter(f2);
            pw = new PrintWriter(fw);


            pw.println(mapwidth);
            pw.println(mapheight);

            for(int i = 0; i < overview.s.toArray().length; i ++){
                pw.println(overview.s.get(i).getID());
            }



        }catch(IOException e){
            e.printStackTrace();
            System.out.println("ERROR!!!");
        }finally{

            pw.close();
        }
    }

I have been trying to do this for ages but cant figure it out.

Upvotes: 1

Views: 292

Answers (2)

shlomi33
shlomi33

Reputation: 1568

Just do:

if (pause.save) {
        Formatter f;
        FileWriter fw;
        PrintWriter pw = null;

        File f2 = new File("docs/save.txt");

        FileReader r;
        BufferedReader r1;
        try{


            //f = new Formatter("docs/save.txt");

            f2.createNewFile();

            fw = new FileWriter(f2);
            pw = new PrintWriter(fw);


            pw.println(mapwidth);
            pw.println(mapheight);

            for(int i = 0; i < overview.s.toArray().length; i ++){
                pw.print(overview.s.get(i).getID());
                if ((i + 1) % 50 == 0) {
                    pw.println();
                }
            }



        }catch(IOException e){
            e.printStackTrace();
            System.out.println("ERROR!!!");
        }finally{

            pw.close();
        }
    }

Upvotes: 1

Devavrata
Devavrata

Reputation: 1795

You can do this in following way:-

for(int i = 0; i < overview.s.toArray().length; i ++){
      pw.println(overview.s.get(i).getID());
      if(i!=0&&i%50==0)
      //newline here
}

Upvotes: 3

Related Questions