1 Replies - 4792 Views - Last Post: 10 May 2010 - 12:44 PM Rate Topic: -----

#1 Th0rn0  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 8
  • Joined: 13-October 07

Saving a vector to file and reading it

Posted 10 May 2010 - 11:01 AM

Hey all,

I'm currently creating a program that I need to save a vector to a file (.dat or .txt) when I click the save button. I also need it to read a file and populate a vector with the same format when I click Load. I have the mouseevent listeners set up I just can't figure out how to get it to save/load. I've search the web and so far it either just creates a text file
			PrintWriter output = null;
			Scanner  scanner = null;
		
			File confidential = new File(fileName);
			 // check that the file doesn't already exist
		if(!confidential.exists())
		{
			try 
			{
				output = new PrintWriter(confidential);
			}
			catch (FileNotFoundException e)
			{ 
   				System.out.println("Error ? problem creating the file!Program closing");
   				System.exit(0);  // this terminates the program
			}
        	

			while( scanner.hasNext())  // while there is more input for the Scanner
			{
				String name = scanner.next();
				int mark = scanner.nextInt();
				output.println( name + " " + mark);  
			}
			
			// tidy up and close the file
		 	output.close();
		}
		
		else
		{
			System.out.println("The file already exists, program is closing");
		}


or it creates a load of jibberish
			try {
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
    			ObjectOutputStream oos = new ObjectOutputStream(baos);
    			oos.writeObject(vehicles);
    			oos.close();
			} catch (IOException ex) {
				System.out.println("Error");
			} 


I am a novice at java programming but I try my best ;D

Thanks for the help.

Is This A Good Question/Topic? 0
  • +

Replies To: Saving a vector to file and reading it

#2 DaneAU  Icon User is offline

  • Great::Southern::Land
  • member icon

Reputation: 286
  • View blog
  • Posts: 1,619
  • Joined: 15-May 08

Re: Saving a vector to file and reading it

Posted 10 May 2010 - 12:44 PM

Well i am not sure what your Vector type is, however to read and write you will essentially need to make use of Scanner, StringTokenizer ~ for reading and PrintWriter to write your output....

So to Write to a file...
import java.io.*;

class Writing {

  public static void main(String[] args) {
	try {
             PrintWriter pw = new PrintWriter( new File("info.txt") );
	     pw.write("testing tokenizer example");
	     pw.close();
	} catch (IOException ioe ) { ioe.printStackTrace(); }
  }
}




And to Read the file you just wrote...
import java.util.Scanner;
import java.util.StringTokenizer;

class Reading {

  public static void main(String[] args) {

      try {
           Scanner reader = new Scanner( new File("info.txt") );
	  
	   do {
		String tmp = reader.nextLine();
                StringTokenizer st = new StringTokenizer(tmp);
                while ( st.hasMoreTokens() ) {
			System.out.println("Token of ("+tmp+") :: "+ st.nextToken() );
                }
        
           } while ( reader.hasNextLine() );


      } catch ( FileNotFoundException fne ) { fne.printStackTrace(); }

  }

}


The output from executing the code

Quote

Token of (testing tokenizer example) :: testing
Token of (testing tokenizer example) :: tokenizer
Token of (testing tokenizer example) :: example


So if you are trying to write a Vector to file, you will need to Iterate it in this case, so for example, say you have a basic class Person

class Person {
  private String name_first;
  private String name_last;

  public Person( String name_f, String name_l ) {
     name_first = name_f;
     name_last = name_l;
  }
  
  @Override
  public String toString() {
    return ( name_first + " " + name_last);
  }
} 



You would create the vector and fill it like so
Vector<Person> persons = new Vector<Person>();
person.add( new Person("Joe", "Blogs") );
/// etc... 


Then to print it, to console you would do
for ( int i = 0; i < persons.size(); i++ ) {
   System.out.println( persons.get(i).toString() );
}


So adapting this you can see how you would write it to file using the exact same principles, also reading from file - you can see how the StringTokenizer will break up each line into Tokens which you can then use in your instantiation of an Object Person as Parameters of the Constructor.

I will leave it at that for now, post if you have any further issues.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1