如何在Java中将二进制数据输出到文件? [英] How to output binary data to a file in Java?

查看:1901
本文介绍了如何在Java中将二进制数据输出到文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据写入二进制格式的文件以进行压缩。数据完全由浮点组成,所以我决定将数据量化为0到65535之间的整数,这样数据就可以写成两位无符号整数,最终节省空间。但是,我需要将量化数据输出到二进制文件而不是人类可读的Ascii。

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包含已经量化的数据的文件作为.txt文件中的字符串

@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);

然而,它将文件写为人类可读的字符串。我需要将它写成二进制数据。怎么用Java做这个呢?

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?

推荐答案

也许这个片段会有所帮助。

Maybe this fragment will help.

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

这篇关于如何在Java中将二进制数据输出到文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆