After my poor showing yesterday I was ready to quit, but I decided this morning I would rather feel dumb than feel like a quitter, so here I am.

I coded this last night thinking if it worked great, if not then I would just drop it. Well it worked ... kind of.

I want to write my JList to a file on the harddrive, so I created a button that does this, and the file is created just fine, in the same directory as all my classes and java files. Not where I want it. I tried changing the path to a c:\data\ directory, but my method will not put the file there, even if I manually create the directory it will not do it.

private void btnSaveActionPerformed(ActionEvent evt)
		{
			FileOutputStream out; // declare a file output object
			PrintStream p; // declare a print stream object
			
			try
				{
				// create a new file output stream
				// connected to "myfile.txt"
				out = new FileOutputStream("inventory.dat");	
				
				// connect print stream to the output stream
				p = new PrintStream(out);
				
				p.println (listModel);
				p.close();
			   }
			
				catch (Exception e)
				{
				System.err.println ("Error writing to file");
				}
		}// end SAVE

Why can I not change location of my output? And if I can, can I make JAVA create the directory for me if it is not already there?

this is your problem out = new FileOutputStream("inventory.dat"); .
Try this and see what happends out = new FileOutputStream("C:" + File.separator + "inventory.dat");

Just for future reference, you can't give Java a relative reference to a file and expect it to create a file with an absolute reference.

"inventory.dat" will be created in the folder that you are running java from (relative reference, relative to the creating location)

"C:\inventory.dat" will be created in the C: (absolute reference, doesn't matter where the creator is)

Thanks for the tip on relative and absolute references.
I added to your line with this:

out = new FileOutputStream("C:" + File.separator + "data" + File.separator + "inventory.dat");

In order to get it down one more level into my DATA folder. It works, as long as the data folder is present upon execution.

Can I not make Java create that folder if it is not already present?

public void createFile(String in)
    {
      toWork = new File(in);
      try
      {
      if(toWork.exists() == false)
      {
        System.out.println("DNE");
        toWork.createNewFile();
      }
      if(toWork.canRead() == false)
      	System.out.println("Read error.");
      if(toWork.canWrite() == false)
      	System.out.println("Write error.");
      }
      catch(Exception e){}
    }

That was an handling function I had for an old network isntant messaging program I wrote. Try doing the same thing, creating the FileOutputStream object from a File object after checking if the directory/file exists. If it doesn't exist, use the "mkdir()" method from File to create the directory.

Something new. It did not error durning compile. good sign. It did not error during test run, another good sign.
It did not create file or directory either though! :D
I have done a lot of wrong stuff out here, but I cannot wait to see how I managed this.

// SAVE		
		private void btnSaveActionPerformed(ActionEvent evt)
		{
			
			File toWork = new File("C:" + File.separator + "data" + File.separator + "inventory.dat");

					
			try
				{
				if(toWork.exists() == false)// if file and directory do not exist
				{
				toWork.mkdir();// make directory
				toWork.createNewFile();  // create file 
				System.out.println(listModel);  // print list to file
							   }
				if(toWork.canRead()== false) 
					System.out.println("Read Error.");
				if(toWork.canWrite() == false) 
					System.out.println("Write error.");
				}
				catch (Exception e){}
			
				
		}// end SAVE

p.s. I tried the file name both ways, just incase I misunderstood what you told me earlier.

No, Java can't create directories under DOS for the very simple reason that Java doesn't work under DOS.

I am most confused then, because I am supposed to use exception handling to create the file and directory if they do not exist.

Maybe I will just put up a message if it is not there telling the user to create it manually and then try again.

Actually, as I continued to play with it I DID get it to create my data directory by altering this line.
File toWork = new File("C:" + File.separator + "data");

Only problem is that my string now prints to the screen in stead of a file.

OK, with the fileoutput stream I was able to write the file, but not create the directory.
With the new File statement I am able to create the directory but not write the file.

When I put both in, neither works.

Anyone?

OK, with the fileoutput stream I was able to write the file, but not create the directory.

Use a separate File object for the directory. Java treats files and directories both as File.

With the new File statement I am able to create the directory but not write the file.

Your code wrote to the console - just like you told it to.

System.out.println(listModel);

I assume you are working from a class example, but you are replacing crucial pieces with chunks of example code here with no thought to what they are actually doing.

Ez-
That is not entirely true. I do not replace any code without thinking it through. The problem for me is that, besides here, I have absolutley NO instruction on how to do any of this. A month ago I did not even know what a method was.
I am taking an online course with lord only knows how many other students, and IF I get a reply back from the instructor on a question, it is two days later.
The extent of this class was to buy a book, read it, and turn in assignments from the syllabus. The instructor graded them, and gave back the "recommended way" of doing it.
So it is not that I am not thinking about what I am doing, I just do not have the tools to put together the correct thought processes yet. I still do not understand how alot of it works together. I understand bits and pieces.
I am trying alot of stuff, and being a troubleshooter, I then simply try to work out the errors to gain a working product.
I know it is not the best way, and out here it is more error than trial, but I really have no other method to learn from right now.
My class is over and done, I have a week to code this app with X number of working methods out of the book to work, I have already surpassed that number ... primarily with your help.
I know I am not good, I know I do not "get it" yet when it comes to most things, but that is why I am continually out here trying to figure out more stuff.
I tried mixing my two methods to see if I could cut out some of the code, 1 did 1 thing, the other did the other, I wanted to see if I could make one do both. I could not, so I have implemented both, and it appears to be working.
the first try creates my folder, the second puts my inventory.dat file in that folder. I learned several things doing it this way.
I know it is aggravating for you to have to spoon feed me every step of the way, and if you never replied to another of my questions I would have nothing but good things to say about you. I really have learned more from you than I have from the class. I just wish I could do it a different way.
Working block

// SAVE		
		private void btnSaveActionPerformed(ActionEvent evt)
		{
			File toWork = new File("C:" + File.separator + "data");

					
			try
				{
				if(toWork.exists() == false)// if file and directory do not exist
				{
				toWork.mkdir();// make directory
				toWork.createNewFile();  // create file 
				}
				if(toWork.canRead()== false) 
					System.out.println("Read Error.");
				if(toWork.canWrite() == false) 
					System.out.println("Write error.");
				}
				
				catch (Exception e){}

				
			FileOutputStream out; // declare a file output object
			PrintStream p; // declare a print stream object
			
			try
				{
				// create a new file output stream
				// connected to "inventory.dat"
				out = new FileOutputStream("C:" + File.separator + "data" + File.separator + "inventory.dat");
	
				
				// connect print stream to the output stream
				p = new PrintStream(out);
				
				p.println (listModel);
				p.close();
			   }
					catch (Exception e)
				{
				System.err.println ("Error writing to file");
				}	
				
		}// end SAVE

Ez-
That is not entirely true. I do not replace any code without thinking it through. The problem for me is that, besides here, I have absolutley NO instruction on how to do any of this. A month ago I did not even know what a method was...

My apologies for the particular choice of words.

Glad you got it to work. A couple of suggestions:

// SAVE        
        private void btnSaveActionPerformed(ActionEvent evt)
        {
            // use variable names that have meaning in your context
            File dataDir = new File("C:" + File.separator + "data");
                    
            try
            {
                if( !dataDir.exists() )// shorter expresion with ! operator
                {
                   dataDir.mkdir();// make directory
                   // toWork.createNewFile();  // create file (don't need)
                }
                if( !dataDir.canRead() ) 
                    System.out.println("Read Error.");
                if( !toWork.canWrite()) 
                    System.out.println("Write error.");
                }
                
                catch (Exception e){
                 // generally not good to catch exceptions and do nothing
                }   

                
            FileOutputStream out; // declare a file output object
            PrintStream p; // declare a print stream object
            
            try
                {
                // create a new file output stream
                // connected to "inventory.dat"
                // can use dataDir here and just append file name
                out = new FileOutputStream(dataDir + File.separator + "inventory.dat");
                
                // connect print stream to the output stream
                p = new PrintStream(out);
                
                p.println (listModel);
                p.close();
               }
               catch (Exception e)
                {
                  System.err.println ("Error writing to file");
                }    
                
        }// end SAVE

Have you looked at the output in your data file yet? It might not be what you expect because the entire listModel.toString() is being dumped to the println() method. You may want to write each cd individually

for (int i=0; i<listModel.size(); i++) {
  p.println( listModel.getElementAt(i).toString() );
}

which would put your toString() description of each cd onto it's own line. It the data needed to be retrieved and loaded later, you would probably want to write each item as comma or tab separated values (i.e. name, artist, price, etc.), but that is a different consideration.

Thanks Ez.
That is the kind of stuff it would take me a year to learn otherwise.
It also gave me some ideas of things I want to do when I get back off vacation and start cleaning up this whole app.
As always, you are a great help.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.