How to output binary data to a file in Java?

回眸只為那壹抹淺笑 提交于 2019-12-18 11:09:09

问题


I'm trying to write data to a file in binary format for compression. The data consists entirely of floating points so I decided to quantize the data to an intergers between 0 and 65535 so the data can be written as two bit unsigned integers and ultimately save space. However, I need to output that quantized data to a file in binary instead of human-readable Ascii.

At the moment this is what I'm doing

@param outputFile the file containing the already quantized data as strings in a .txt file

public void generateBinaryRioFile(String materialLibrary,
        String outputFile, String group, String mtlAux) {

    try {

        // Create file
        FileWriter fileStream = new FileWriter(outputFile);
        try {

            BufferedReader br = new BufferedReader(new FileReader(new File(
                    "idx.txt")));

            while ((line = br.readLine()) != null) {
                writer.write(line + "\n");
            }
            try {
                br.close();

            } catch (FileNotFoundException e) {
                e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
            }           BufferedWriter writer = new BufferedWriter(fileStream);

However that writes to the file as a human readable string. I need it to be written as binary data. How does one go about doing this in Java?


回答1:


Maybe this fragment will help.

 int i = 42;
 DataOutputStream os = new DataOutputStream(new FileOutputStream("C:\\binout.dat"));
 os.writeInt(i);
 os.close();



回答2:


What about the DataOutputStream. You can write int which contains 2 of your data integers.

DataOutputStream dos = new DataOutputStream(new FileOutputStream(<path>));
ArrayList<Integer> list = new ArrayList<Integer>();
int sum;
for( int i = 0; i < list.size(); i++ ) {
    if(i%2!=0){
        sum |= list.get( i ).intValue()<<16;
        dos.writeInt( sum );
    } else {
        sum = list.get( i ).intValue();
    }
}


来源:https://stackoverflow.com/questions/6981555/how-to-output-binary-data-to-a-file-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!