LeopardL GD
LeopardL GD

Reputation: 132

Create a binary file in java

These are the related questions that might cause my question to be closed, even though I specify another question:

And now to the point. I've got a file with a specific extension, to be more exact it's .nbs. I want to create a file and then write the specific data to it.
That might have sounded vague so let me show you the code I have started with.

try {
    File bpdn = new File(getDataFolder() + "song.nbs");
    if (!bpdn.exists()) {
        bpdn.createNewFile();
    }

    FileOutputStream fos = new FileOutputStream(bpdn);

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

I'll provide you even more details. So I've got a song.nbs file that I have created in the past, for myself. And now, whenever a person runs my application, I want it so there's a new song.nbs file with the exact contents of a file that I have on my PC right now. Therefore, I need to somehow get the bytes of my existing song.nbs and then copy and paste them in my Java application... or is it the way? I neither know how to get the bytes of my own file right now, nor do I know how to write them.

Upvotes: 3

Views: 4350

Answers (2)

LeopardL GD
LeopardL GD

Reputation: 132

I think I came up with a solution, but I am not sure if this is works. I'd appreciate if you would take a look.

try {
    File bpdn = new File(getDataFolder() + "badpiggiesdrip.nbs");
    if (!bpdn.exists()) {
        bpdn.createNewFile();
    }

    FileOutputStream fos = new FileOutputStream(bpdn);
    fos.write(new byte[] {
            Byte.parseByte(Arrays.toString(Base64.getDecoder().decode(Common.myString)))
    });

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

Common.myString is just a string, that contains data of this type:

(byte) 0x21, (byte) 0x5a, .....

and it's encoded in Base64.

Upvotes: -1

enzo
enzo

Reputation: 11496

You need to create a resources folder. More info here.

Assuming your project structure is

ProjectName/src/main/java/Main.java

you can create a resources folder inside main/:

ProjectName/src/main/java/Main.java
ProjectName/src/main/resources/

Move your song.nbs you want to read inside resources/:

ProjectName/src/main/java/Main.java
ProjectName/src/main/resources/song.nbs

Now, get the InputStream of song.nbs stored there:

final ClassLoader classloader = Thread.currentThread().getContextClassLoader();
final InputStream is = classloader.getResourceAsStream("song.nbs");

Then, write this input stream to your new file:

final File bpdn = new File(getDataFolder() + "song.nbs");
if (!bpdn.exists()) bpdn.createNewFile();
final FileOutputStream os = new FileOutputStream(bpdn);

byte[] buffer = new byte[1024];
int read;
while ((read = is.read(buffer)) != -1) {
    os.write(buffer, 0, read);
}

Upvotes: 3

Related Questions