简体   繁体   English

从使用字节流写入的文件中读取

[英]Reading from a file written to using a byte stream

So I've written a series of Integer values between 0 and 100000 into a text file using a byte stream, to ensure that they have been stored in the correct format I'm trying to use Input Stream to view the numbers. 因此,我已使用字节流将一系列介于0到100000之间的Integer值写入文本文件,以确保它们以正确的格式存储,我试图使用Input Stream来查看数字。 I've tried several ways, however each time the numbers that I print out are incorrect, can anyone see where I'm going wrong, or have any ideas about alternative methods of reading the input stream: 我尝试了几种方法,但是每次我打印出的数字不正确时,任何人都可以看到我要去的地方吗,或者对读取输入流的替代方法有任何想法:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.Random;


public class Question1ByteStream {
    public static void main(String[] args) throws IOException {
        //************************************************************
        //WRITING TO THE FILE

        FileOutputStream out = null;
        try {
            out = new FileOutputStream("ByteOutStream.txt");
            for(int i = 0; i < 10000; i ++){
                Integer randomNumber = randInt(0, 100000);
                byte[] bytes = ByteBuffer.allocate(4).putInt(randomNumber).array();
                out.write(bytes);
            }
        }finally{
            if (out != null) {
                out.close();
            }
        }
        //***********************************************************
        //READING BACK FROM THE FILE

        FileInputStream in = null;

        try {
            in = new FileInputStream("ByteOutStream.txt");
            int c;

            while ((c = in.read()) != -1) {
                out.write(c);
            }
        } finally {
            if (in != null) {
                in.close();
            } 
        }

    }

    //***************************************************************
    public static int randInt(int min, int max) {
        Random rand = new Random();
        int randomNum = rand.nextInt((max - min) + 1) + min;

        return randomNum;
    }
}

Use DataInputStream.readInt(). 使用DataInputStream.readInt()。

You can write the integers much more simply with DataOutputStream.writeInt(). 您可以使用DataOutputStream.writeInt()更简单地编写整数。 Use buffered streams between the data stream and the file stream when both reading and writing. 读写时在数据流和文件流之间使用缓冲的流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM