Alex Bidenia
Alex Bidenia

Reputation: 29

I can't write on multiple lines in a txt file in java

So I'm trying to write in a text file, nothing too complicated, but for some reason the new text that i want to add doesn't change lines, it keeps going on the same line, and I can't figure out why. The irrelevant parts are being commented so don't worry about them.

import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class Main {
    public static void main( String args[]) {
         int a = 32;
         int b=12;
         int c=33;

          List<Integer> myList = new ArrayList();
          myList.add(a);
          myList.add(b);
          myList.add(c);
         /* for(int s:myList)
          {
              System.out.println(s);
          }
          */
          //Om ar= new Om("Alex",21,185);
          //System.out.println(ar);

          try{
              File myObj = new File("filename.txt");
              if(myObj.createNewFile()){
                  System.out.println("File created " + myObj.getName());

              }
              else
              {
                  System.out.println("File already exists");
              }

          }
          catch (IOException e)
          {
              System.out.println("An error has occurred");
              e.printStackTrace();
          }
         
          
          try {
            FileWriter myWriter = new FileWriter("filename.txt");
            for(int i=1;i<10;i++)
            {
            myWriter.append("This is a new file, nothing sus here."+i + " ");
            }
            myWriter.close();
            System.out.println("Successfully wrote to the file.");
          } catch (IOException e) {
            System.out.println("An error occurred.");
            e.printStackTrace();
          }
                
    }
    
}

Upvotes: 0

Views: 143

Answers (1)

camickr
camickr

Reputation: 324118

  1. Wrap your FileWriter in a BufferedWriter to make writing to the file more efficient.
  2. Then you can use the newLine() method of the BufferedWriter to add a newline String to the file as you require. The newLine() method will write out the appropriate string for your current platform.

Upvotes: 1

Related Questions