0

I just started learning how to write into file and read from a file on java oi. Now I can write simple text into a file and also can read it using system.out.print. The problem now is, I tried to create an array and store it in a file using the same way I learnt, but when I run the program the file is created but there was nothing to display. Please is there any thing I can do otherwise, below is the sample of my codes:

public static void main(String[] args) throws FileNotFoundException {
    // TODO Auto-generated method stub
    File Veggies= new File ("C:\\Users\\user\\Desktop\\My Java Files\\Product.txt");
    if(Veggies.exists())
        System.exit(0);     

    PrintWriter output= new  PrintWriter(Veggies);
    output.println("These are the list of our products.");


    String[] VeggiesArray={"Apples","Bananas","Oranges","Avocados","Strawberries"};
    for(int i=0;i<=VeggiesArray.length;i++){
        output.println("(" + i + ")" +" "+ VeggiesArray[i]);
    }

    output.close();
}
azro
  • 53,056
  • 7
  • 34
  • 70
  • What are you trying to do with the Veggies.exists()? I believe that will exit immediately after creating the file. – Arne Saupe Feb 02 '19 at 21:13
  • Please follow Java naming conventions : packages, attributes, variables, parameters, method have to start in **lowerCase**, while class, interface should start in **UpperCase** – azro Feb 02 '19 at 21:19
  • You're likely going to run into a `IndexOutOfBoundsException` with `i<=VeggiesArray.length`, as arrays are `0` indexed, meaning the statement should read more like `i < VeggiesArray.length` – MadProgrammer Feb 02 '19 at 21:58

1 Answers1

0
    File veggies= new File (".\\Product.txt"); 

    PrintWriter output= new PrintWriter(veggies); 
    output.println("These are the list of our products."); 

    String[] veggiesArray={"Apples","Bananas","Oranges","Avocados","Strawberries"}; 
    for(int i=0;(i<veggiesArray.length);i++) { 
        output.println("(" + i + ")" +" "+ veggiesArray[i]); 
    } 
    output.close(); 

Got rid of the veggies.Exists() because it would only allow you to generate the file one time, without first deleting it.

Fixed the loop condition as MadProgrammer pointed out.

Arne Saupe
  • 111
  • 5