SamW
SamW

Reputation: 109

Reading a file using FileInputStream

Firstly, I use FileOutputStream to write an big integer into the file.

e.g.

int a = 2051741;
fileA.write(a);

Then later, when I use FileInputStream to read the data.

e.g.

int b = fileA.read();

When I printout b, it would be something small like 112

Why does that happen? How can I readout the original integer?

Upvotes: 2

Views: 940

Answers (3)

pouyan021
pouyan021

Reputation: 189

You can use a Scanner for reading your file's contents:

 Scanner s = new Scanner(file)
 int b = s.nextInt();
 System.out.print(b);

This is for reading a single value from a file,here's an approach for times when your file has more than one value:

 while(s.hasNext()){
       int b[i] = s.nextInt();
       i++;
       }
     for(int x:b)
     System.out.print(b);

You may also use methods like nextBigInteger() for big integer values.

Upvotes: 0

Tunaki
Tunaki

Reputation: 137064

FileInputStream and FileOutputStream handles bytes of data. More specifically, read() reads a single byte and write(int) writes a byte.

The Javadoc of OutputStream.write(int) says:

Writes the specified byte to this output stream. The general contract for write is that one byte is written to the output stream. The byte to be written is the eight low-order bits of the argument b. The 24 high-order bits of b are ignored.

This means that when you are giving an int value, the 24 high-order bits of bit are ignored. Taking your argument of 2051741, dropping the 24 high-order bits, you come down to 2051741 & 0xFF = 157.

Which is what you end up reading: a small number like 157.

Upvotes: 0

WalterM
WalterM

Reputation: 2706

public void write(int b) throws IOException

Writes the specified byte to this file output stream. Implements the write method of OutputStream.

You need to decorate your OutputStream with another type of OutputStream that supports it. i.e. DataOutputStream

    DataOutputStream out = new DataOutputStream(new FileOutputStream("MyFile.txt"));
    out.writeInt(20);
    out.writeInt(53432542);
    out.writeLong(5234843258938L);
    out.close();

    DataInputStream in  = new DataInputStream(new FileInputStream("MyFile.txt"));
    System.out.println(in.readInt());
    System.out.println(in.readInt());
    System.out.println(in.readLong());
    in.close();

Upvotes: 2

Related Questions