Main class cannot find .dat file

I am doing a simple exercise where a program reads data from a .dat file and prints it out on the console.

I am working with NetBeans. I saved the .dat file in the default package folder where the main file is located. And it cannot find the .dat file.

Here are the codes:

import java.nio.*;
import java.nio.channels.*;
import java.nio.charset.*;
import java.io.*;

public class BufferConverter {
    public static void main(String[] arguments) {
        try {
            // read byte data into a byte buffer
            String data = "friends.dat";
            FileInputStream inData = new FileInputStream(data);
            FileChannel inChannel = inData.getChannel();
            long inSize = inChannel.size();
            ByteBuffer source = ByteBuffer.allocate( (int) inSize );
            inChannel.read(source, 0);
            source.position(0);
            System.out.println("Original byte data:");
            for (int i = 0; source.remaining() > 0; i++) {
                System.out.print(source.get() + " ");
            }
            // convert byte data into character data
            source.position(0);
            Charset ascii = Charset.forName("US-ASCII");
            CharsetDecoder toAscii = ascii.newDecoder();
            CharBuffer destination = toAscii.decode(source);
            destination.position(0);
            System.out.println("\n\nNew character data:");
            for (int i = 0; destination.remaining() > 0; i++) {
                System.out.print(destination.get());
            }
            System.out.println();
        } catch (FileNotFoundException fne) {
            System.out.println(fne.getMessage());
        } catch (IOException ioe) {
            System.out.println(ioe.getMessage());
        }
    }
}

Should I write a specific path? How can I make the program find the .dat file?

Any help is much appreciated Sylvain

Jon Skeet
people
quotationmark

I am working with NetBeans. I saved the .dat file in the default package folder where the main file is located. And it cannot find the .dat file.

Presumably that folder isn't the same as the working directory when you launch it.

Use System.out.println(new File(".").getAbsolutePath()); to see where you're running, and then either use a filename relative to that, or work out how to persuade Netbeans to copy the file to the appropriate place (e.g. have it in a resources directory, which I believe counts as resources to copy).

people

See more on this question at Stackoverflow