binary file writing and reading

Im looking around the net for a file write and read example and ive got an implementation using DataOutputStream and DataInputStream but its not really working, Could someone please explain an easy way to do this, or explain DataOutputStream a little for me? Its giving me a file not found exception but it shouldnt be.

DataOutputStream and DataInputStream are pretty much self explanatory I’m afraid. You write data, you read data, It Just Works. At least, I’ve never had any problems.
Fortunately, your problem is not with the data streams - you’re trying to open a file which doesn’t exist.

Post the full exception and the relevant code that triggers it.

Sorry for asking such ambiguous questions, but thankyou for the reply!
Ive got it sorta half working…

Maybe something more direct like =>

a) How do you create a file in java? (the exception was file not found)
b) Where does this file go on the disk
c) Once its running on the net as an applet, where is the file going to be located now? Im just a little confused.
d) could you post a simple example of how to catch an IOException?


// (this is a representation of a file, just an object in RAM, not on disk)
File file = new File("C:/Program Files/MyProduct.txt");

// now we are going to write a file. If it doesn't exist, it will be created (!)
OutputStream out = new FileOutputStream(file);

// write the plain text alphabet to a file.
byte[] data = new byte[26];
for(int i=0;i<26; i++)
   data[i] = (byte)('a'+i);

out.write(data);
out.flush(); // sync the file-descriptor
out.close(); // close the file-descriptor

Where you tell it to. Just like in C. You have relative and absolute paths.

Won’t work with applets. See my reply in your other thread.

try
{
    if(!file.exists()) // or whatever you which to do
      throw new FileNotFoundException(); // this is a subclass of IOException
}
catch(IOException exc)
{
   exc.printStackTrace(); // for easy debugging
}

Besides that,


File file = new File("your path");
new FileInputStream(file); 

will throw a FileNotFoundException if the file does not exist.

Thankyou Riven.
Its a pity what you told me tho, so I cant even load a game level!

you can, by uploading/downloading to/from a server (with a php script)

Thanks for the help, but I tried the code you said that would create the file and it
just said “file not found” the same!
Can you tell me whats wrong with this? Its just exceptioning out.
Maybe there is nothing wrong with it and im stuffing something else up.


public void save_map()
 {
  String FILENAME = "map.map";
  DataOutputStream os = new DataOutputStream(new FileOutputStream(FILENAME));
  os.writeInt(bstones); 
  int i;
  int j;
  for(i=0;i<bstones;i++)
  {
   os.writeFloat(bstone[i].fillet_dist);
   os.writeFloat(bstone[i].fillet_depth);
   os.writeFloat(bstone[i].depth);
   os.writeInt(bstone[i].loop_vs);
   for(j=0;j<bstone[i].loop_vs;j++)
   {
    os.writeFloat(bstone[i].loop_v[j].x);
    os.writeFloat(bstone[i].loop_v[j].y);
    os.writeFloat(bstone[i].loop_v[j].z);
   }
   os.writeInt(bstone[i].vs);
   os.writeInt(bstone[i].ts);
   for(j=0;j<bstone[i].vs;j++)
   {
    os.writeFloat(bstone[i].v[j].x);
    os.writeFloat(bstone[i].v[j].y);
    os.writeFloat(bstone[i].v[j].z);
   }
   for(j=0;j<bstone[i].ts;j++)
   {
	os.writeInt(bstone[i].t[j].i[0]);
	os.writeInt(bstone[i].t[j].i[1]);
	os.writeInt(bstone[i].t[j].i[2]);
	os.writeInt(bstone[i].t[j].col);
    os.writeFloat(bstone[i].t[j].nor.x);
    os.writeFloat(bstone[i].t[j].nor.y);
    os.writeFloat(bstone[i].t[j].nor.z);
   }
  }

  os.writeInt(blights);
  for(i=0;i<blights;i++)
  {
   os.writeFloat(blight[i].pos.x);
   os.writeFloat(blight[i].pos.y);
   os.writeFloat(blight[i].pos.z);
   os.writeFloat(blight[i].power);
  }
  
  os.close();
 }
 
 public void load_map()
 {
  String FILENAME = "map.map";
  DataInputStream os = new DataInputStream(new FileInputStream(FILENAME));
  int k;
  int j;
  
  bstones=os.readInt(); 
  int i;
  for(i=0;i<bstones;i++)
  {
   bstone[i].fillet_dist=os.readFloat();
   bstone[i].fillet_depth=os.readFloat();
   bstone[i].depth=os.readFloat();
   bstone[i].loop_vs=os.readInt();
   bstone[i].loop_v=new vector[bstone[i].loop_vs];
   for(k=0;k<bstone[i].loop_vs;k++) bstone[i].loop_v[k]=new vector();
   for(j=0;j<bstone[i].loop_vs;j++)
   {
	bstone[i].loop_v[j].x=os.readFloat();
	bstone[i].loop_v[j].y=os.readFloat();
	bstone[i].loop_v[j].z=os.readFloat();
   }
   bstone[i].vs=os.readInt();
   bstone[i].ts=os.readInt();
   bstone[i].v=new vector[bstone[i].vs];
   for(k=0;k<bstone[i].vs;k++) bstone[i].v[k]=new vector();
   bstone[i].t=new tri[bstone[i].ts];
   for(k=0;k<bstone[i].ts;k++) bstone[i].t[k]=new tri();
   for(j=0;j<bstone[i].vs;j++)
   {
	bstone[i].v[j].x=os.readFloat();
	bstone[i].v[j].y=os.readFloat();
	bstone[i].v[j].z=os.readFloat();
   }
   for(j=0;j<bstone[i].ts;j++)
   {
	bstone[i].t[j].i[0]=os.readInt();
	bstone[i].t[j].i[1]=os.readInt();
	bstone[i].t[j].i[2]=os.readInt();
	bstone[i].t[j].col=os.readInt();
	bstone[i].t[j].nor.x=os.readFloat();
	bstone[i].t[j].nor.y=os.readFloat();
	bstone[i].t[j].nor.z=os.readFloat();
   }
  }

  blights=os.readInt();
  for(i=0;i<blights;i++)
  {
   blight[i].pos.x=os.readFloat();
   blight[i].pos.y=os.readFloat();
   blight[i].pos.z=os.readFloat();
   blight[i].power=os.readFloat();
  }

  os.close(); 
 }

If the file doesn’t exist yet, just do this:

try{
 FILENAME.createNewFile();
}catch(IOException ex){
 ex.printStackTrace();
}

See: http://java.sun.com/javase/6/docs/api/java/io/File.html#createNewFile()

Sun’s java tutorial is pretty good on this stuff, worth a look:
http://java.sun.com/docs/books/tutorial/essential/index.html

That won’t help at all. If you are going to read data from a file that doesn’t exist, it won’t really help you much creating an empty file right there…

But it doesnt work if im reading or writing, I actually havent even tested the read yet because I havent been able to write anything to read!

Ok, I got the file to create, it went into the bin directory (thats the relative directory I just found out) But the rest of the code still doesnt work it goes file not
found if the file is there or not, so writing the way I’ve done it doesnt work.

I have no idea what problem you are having. It sounds like you are trying to read before you have written the file, but we shouldn’t have to guess. Post the exception if you are getting one. The code you were given works, eg:

static public void main (String[] args) throws IOException {
	String fileName = "map.map";

	DataOutputStream output = new DataOutputStream(new FileOutputStream(fileName));
	output.writeInt(123);
	output.close();

	DataInputStream input = new DataInputStream(new FileInputStream(fileName));
	int value = input.readInt();
	input.close();
	System.out.println(value);
}

Maybe “./map.map” is a directory. That will throw a FileNotFoundException in the FileOutputStream constructor too.

This works for me. Adapt it to your method and it should work. Like Riven says, creating the file won’t help if you’re reading (but here we’re writing).

import java.io.*;

public class Test{
	public static void main(String[] args){
		
		//To do a write, do what Riven said before,  but create the file if it isn't there:
		
		// (this is a representation of a file, just an object in RAM, not on disk)
		File file = new File(System.getProperty("user.home"), "MyProduct.txt");
                // make sure that the file exists since we're going to write to it.
		if (file.isFile() == false){
			try{
			  file .createNewFile();
			}catch(IOException ex){
				ex.printStackTrace();
			}
		}
		OutputStream out = null;
        try{
            out = new FileOutputStream(file);
			// write the plain text alphabet to a file.
			byte[] data = new byte[26];
			for(int i=0;i<26; i++)
			   data[i] = (byte)('a'+i);
			
			out.write(data);
			out.flush(); // sync the file-descriptor
			out.close(); // close the file-descriptor
        }catch(IOException ex){
			ex.printStackTrace();
        }
        System.out.println("done");
	}
}

That won’t help either.

FileOutputStream(file) will create the file. Doing it manually is not required.

Please excuse me while I go shoot myself… I know, I went through the docs at sun and they are telling me the exact same thing you guys are telling me but its just not working!
“map.map” cant be a directory, its just going “file not found” exception then the rest of it fails afterwards cause I’m not try and catching it.

So you guys have no idea whats going wrong… I tell you what I probably typed it in right FIRST TIME and I shouldn’t have even been here with my problem.

So theres nothing wrong with my code, DAMN IT!

This code here is returning the same error…


FileOutputStream out = null;

  out = new FileOutputStream("map.map");
  int c;

  byte[] data = new byte[26];
  for(int i=0;i<26; i++)
  data[i] = (byte)('a'+i);
  out.write(data);

  out.close();
 

Exception in thread “Thread-4” java.lang.Error: Unresolved compilation problems:
Unhandled exception type FileNotFoundException
Unhandled exception type IOException
Unhandled exception type IOException

at ball.save_map(ball.java:626)
at ball.run(ball.java:1015)
at java.lang.Thread.run(Unknown Source)

The only thing that worked was create file…

Never knew that, ta :slight_smile:

That’s a compilation error… Put your code in a try catch block

Maybe try this tutorial as well: http://java.sun.com/docs/books/tutorial/essential/exceptions/index.html

That’s a compile error. One of your classes can’t compile so Eclipse (or whatever your using) is creating a method that simply throws an exception until you correct the problem. So (in effect) you’re running:


save_map()
{
   throw new Error("Unresolved compilation problems.");
}

Doesnt it only make the “unhandled exception” once the exception happens.
It wouldnt come up with that im not handling the exception if the exception never arose.

Spoon feeding :slight_smile:


import java.io.*;

public class Whatever
{
  public static void main(String[] args)
  {
      try
      {

  byte[] data = new byte[26];
  for(int i=0;i<26; i++)
     data[i] = (byte)('a'+i);

  String path = "map.map";
  File file = new File(path);
  System.out.println("absolute path: " + file.getAbsolutePath());
  System.out.println("exists: " + file.exists());
  System.out.println("is directory: " + file.isDirectory());

  FileOutputStream out = new FileOutputStream(file);
  out.write(data);
  out.close();


      }
      catch(IOException exc)
      {
         exc.printStackTrace();
      }
   }
}