Alright so I have to Save and Load an array, and I am unfortunately running into issues at saving, where it keeps giving me the error

Exception in thread "main" java.lang.NullPointerException
at java.io.FileOutputStream.<init>(FileOutputStream.java:186)
at java.io.FileOutputStream.<init>(FileOutputStream.java:84)
at SocialEventList.saveAppointmentData(SocialEventList.java:41)
at Test.main(Test.java:120)

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


public class SocialEventList {
	private SocialEvent[] thelist = new SocialEvent[10];
	private int i = 0;
	private int counter = 0;
	private String save;
	
	public void add(SocialEvent se){
		if(i<thelist.length){
			thelist[i]=se;
			++i;
			System.out.println(thelist[i]);
		}
	}
	public void display(){
		for(int j = 0; j < i; j++){                         
			System.out.println(thelist[j].toString(i));
		}
	}

	public void occursOn(int month, int day, int year) {
		for(int h = 0; h<i;h++)
		{
			if( month==thelist[h].getMonth()&&day==thelist[h].getDay() &&year==thelist[h].getYear() ) {
				System.out.println("You have event "+h+ " that occurs on the same day, check to make sure you have enough time.");
				display();
			}
			else{
				System.out.println("This event "+h+ " are no two events occur on this same day");
			}
		}
	}		
	public void saveAppointmentData(){
		for(int k = 0; k<i;k++){
		PrintStream out = null;
		try {
			out = new PrintStream(new FileOutputStream(save));
			out.println(thelist[k]);
		}
		catch(FileNotFoundException e){
			System.out.println("Error opening the file ");
			System.exit(0);
		}
	}
	}
}
else if(input.equals("SAVE")){
				sel.saveAppointmentData();
			}

A null pointer exception means you are trying to access a variable, which has not been initialized. The line number is also displayed with the error, so you know which variable the error is about.

Try fixing that, and if you run into trouble, ask me.

Ok I can now have it create a file, but it doesn't have a type(.txt\.rtf) and its name is very crazy, like someone jumped on a keyboard.

public void saveAppointmentData(){
			PrintStream out = null; 
			try {
				out = new PrintStream(new FileOutputStream(toString()));
				out.println(save);
			}
			catch(FileNotFoundException e){
				System.out.println("Error opening the file ");
				System.exit(0);
			}
			finally {
				out.close();
			}
			
	}
out = new PrintStream(new FileOutputStream(toString()));
				out.println(save);

The first line: you give toString() as an argument. toString() is the method that returns a string with the name of your object. You need to give the name of the file.

Are you using eclipse? Eclipse will give you a lot of help when you are writing code, and autocomplete is great.

I am using eclipse and i have switched my code to this, but i am still getting an error.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PrintStream;


public class SocialEventList {
	private SocialEvent[] thelist = new SocialEvent[10];
	private int i = 0;
	private String save="/Users/dlaxman92/Desktop/Java /SocialPlanner2";
	public void add(SocialEvent se){
		if(i<thelist.length){
			thelist[i]=se;
			System.out.println(thelist[i]);
			++i;
		}
	}
	public void display(){
		for(int j = 0; j < i; j++){                         
			System.out.println(thelist[j].toString());
		}
	}

	public void occursOn(int month, int day, int year) {
		for(int h = 0; h<i;h++)
		{
			if( month==thelist[h].getMonth()&&day==thelist[h].getDay() &&year==thelist[h].getYear() ) {
				System.out.println("You have event "+h+ " that occurs on the same day, check to make sure you have enough time.");
				display();
			}
			else{
				System.out.println("This event "+h+ " are no two events occur on this same day");
			}
		}
	}
		public void saveAppointmentData() throws IOException{
			PrintStream out = null;
			for(SocialEvent se:thelist)
			try {
				out = new PrintStream(new FileOutputStream(save));
				out.print(se.toString());
				System.out.println("You have just saved your file ");
			}
			catch(FileNotFoundException e){
				System.out.println("Error opening the file ");
				System.exit(0);
			}
			
			
	}
		
	
	}

What error are you getting?

private String save="/Users/dlaxman92/Desktop/Java /SocialPlanner2";

Two problems. You have to point to a file, not a folder. Also, the program will save to "C:/Users/dlaxman92/Desktop/Java /SocialPlanner2".

If you just use:

private String save="savedFile.txt";

It might work.

Please reply with your results.

making it

private String save="savedFile.txt";

worked, but i still have it displaying the array in memory even though I have my toString() method defined.

public void saveAppointmentData(){
		PrintStream out = null;
			try {
				out = new PrintStream(new FileOutputStream(save));
				out.println(toString());
				System.out.println("You have just saved your file ");
			}
		catch(FileNotFoundException e){
			System.out.println("Error opening the file ");
			System.exit(0);
		}		
	}

Ok i have now switched from just an output stream to an ObjectOutput except I have an error here

ObjectOutputStream ois = ObjectOutputStream(save);

Can anyone tell me why?

public void saveAppointmentData(){
		PrintStream out = null;
			try {
				out = new PrintStream(new FileOutputStream(save));
				ObjectOutputStream ois = ObjectOutputStream(save);
				ois.writeObject(thelist);
				System.out.println("You have just saved your file ");
			}
		catch(FileNotFoundException e){
			System.out.println("Error opening the file ");
			System.exit(0);
		}		
	}

What error are you getting then? The error always says something about the problem.
And what do you mean by the array still shows in memory?

They out print to the text file is the different parts of the array, and there locations in the array.

OK. Say I have got an array with numbers, and I want to print it to a file. I would use this code:

class Test {
int [] myIntArray = new int [5];

public static void main (String[] args){
new Test();
}
Test () {

try {
			BufferedWriter out = new BufferedWriter (new FileWriter ("myTextFile.txt"));
                   for (int i=0; i<myIntArray.length; i++){
			out.write("");
}
			out.close ();
		} catch (FileNotFoundException e) {
			System.out.println("Error!");
		} catch (IOException e) {
			System.out.println("Error!");
		}
}
}

Just try it yourself, and integrate it in your program.

Edited 5 Years Ago by hiddepolen: n/a

OK that works, but now why won't my toString work?

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


public class SocialEvent {
	private String title;
	private String attire;
	private String time;
	private int day;
	private int month;
	private int year;
	private String dayweek;
	private String save;
	
	public SocialEvent(String attire,String dayweek, String title,int day,int month,int year, String time){
		this.attire = attire;
		this.dayweek = dayweek;
		this.title = title;
		this.day = day;
		this.month = month;
		this.year = year;
		this.time = time;
	}
	
	public String getTitle() {
		return title;
	}


	public void setTitle(String title) {
		this.title = title;
	}


	public String getAttire() {
		return attire;
	}


	public void setAttire(String attire) {
		this.attire = attire;
	}


	public String getTime() {
		return time;
	}


	public void setTime(String time) {
		this.time = time;
	}


	public int getDay() {
		return day;
	}


	public void setDay(int day) {
		this.day = day;
	}


	public int getMonth() {
		return month;
	}


	public void setMonth(int month) {
		this.month = month;
	}


	public int getYear() {
		return year;
	}


	public void setYear(int year) {
		this.year = year;
	}


	public String getDayweek() {
		return dayweek;
	}


	public void setDayweek(String dayweek) {
		this.dayweek = dayweek;
	}

	@Override
	public String toString() {
		return "\nTitle: "+title+"\nAttire: "+attire+"\nDate: "+month+"/"+day+"/"+year+"\nDay of the Week: "+
				dayweek+"\nTime: "+time;
	}

}
public void saveAppointmentData(){
		try {
			BufferedWriter out = new BufferedWriter (new FileWriter (save));
			for (int i=0; i<thelist.length; i++){
				out.write(toString());
				System.out.println("File Saved");
			}
			out.close ();
		} catch (FileNotFoundException e) {
			System.out.println("Error!");
		} catch (IOException e) {
			System.out.println("Error!");
		}
	}

Edited 5 Years Ago by Laxman2809: n/a

hey friends ..em new to java...Can anybody tell me..Can We store the data in array permanently?? everytime i run my java code with array as object of class...its previously entered values disappear...:(

@laxman: the problem is which toString() method you call.
You call the one from the object you are working on, and not from the SocialEvent.
This will work:

out.write(theList[i].toString());
// or even easier:
out.write(theList[i]);
// legal because you overrode the toString() method.

@jassikaur The array will be stored in the block you make it in. If you make an array in an if statement, it will not be there after the if statement. If you make an array in a method, you can only use it in that method. If you make one in your class, you can use it throughout your entire class.

If you show a little code with the problem, we can help you further.

Edited 5 Years Ago by hiddepolen: n/a

hey friends ..em new to java...Can anybody tell me..Can We store the data in array permanently?? everytime i run my java code with array as object of class...its previously entered values disappear...:(

You need to write your array to a file before closing your program, and read it back in from the file next time you start the program. That's what this thread is all about.

@Laxman2809
Rather than write your own code to output the data in text form then having to write a parser to read them back in, why not use the standard XLMencoder/decoder classes to write & read your text file in a standard universal format at almost zero effort.
The following little methods will write and read almost any old data structure you can define in Java, no matter how complex and nested - all you need to add is a cast of the read object to SocialEvent[] or whatever. The only significant pre-requisite is that any of your classes that need to be encoded/decoded follow the standard JavaBean conventions with get/set methods for all the fields you want to encode.

public static void writeObjectToXML(Object o, OutputStream out) {
      java.beans.XMLEncoder en = new java.beans.XMLEncoder(out);
      en.writeObject(o);
      en.close();
   }

   public static Object readObjectFromXML(InputStream in) {
      return new java.beans.XMLDecoder(in).readObject();
   }
public class hello
{
    int a;
    int b;

    public hello()
    { 

    }
    public hello(int h,int f)
    { this.a=h;
      this.b=f;

    }
}
-----------------------------------------------------------------------------------------
//main program  i am running in ecllipse using class hello's array object//
import java.util.*;
public class eg {

        public static void main(String[] args) 
       {
        hello[] ab=new hello[20];
        Scanner n=new Scanner(System.in);
        for (int i=0;i<2;i++)
        {
        int d=n.nextInt();
        int f=n.nextInt();
        ab[i]=new hello(d,f);
        }      
        for (int i=0;i<2;i++)
        {System.out.println(ab[i].a + "" +ab[i].b);
        }
        }
    }
/*

in this program when i enter the values in the array ,it perfectly shows me the same entered values in println statement....but the problem is if i run this program again or refresh this....and just try to see the previous values in the array by making 1st loop as comment...it doesnt show dat it shows me 0,0,0,0,0 ...why it is so??plz help me

Edited 3 Years Ago by Nick Evan: Fixed formatting

Your data is stored in the Java Virtual Machine's memory, which gets cleared out when your program is finished. That's how Java works and you can't change it. Please re-read my previous answer to you.

That is because the program does not save the array. When you stop the program, all the variables will be deallocated, and the used memory is restored.

If you want to save the variables, make a file, put the variables in there, and read the numbers from the file into the program on the start (just like the user above me said, using XML).

Yes. Mind, this has nothing to do with arrays. All data is cleared if you close your program. Any variable can be stored in many ways in a file.

This article has been dead for over six months. Start a new discussion instead.