Converting Bytes into Char
I was trying to redo File Input/Output again because I sort of forgot and I ran into a problem.
Code :
import java.io.*;
import java.util.concurrent.TimeoutException;
public class FileIO
{
public static void main(String args[])
{
FileInputStream inputStream = null;
try
{
inputStream = new FileInputStream("X:\\Users\\unCryptifier\\Documents\\Scores.txt");
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
byte readingBytes[] = new byte[24];
char convertedBytes[] = new char[5];
String scores[] = new String[5];
int i = 0;
while (i != -1)
{
try
{
readingBytes[i] = (byte)(inputStream.read());
}
catch (IOException e)
{
e.printStackTrace();
}
System.out.println((char)(i));
}
}
}
The file that I'm trying to open has the numbers 0 to 25 in it with no space or lines in between. When I run the program, nothing shows in my console. It's running but nothing shows up and when I terminate the program, the only output it shows is space. I don't get what the problem is.
Re: Converting Bytes into Char
Quote:
Originally Posted by
unCrypticSolutions
...sort of forgot
You do know that there is extensive on-line documentation, rignt? FileInputStream
I mean, it's always OK to ask, but wouldn't it be more time-effective for you to check the docs?
Anyhow...
Quote:
Originally Posted by unCrypticSolutions
... ran into a problem...
One problem is that the read() function returns an integer, not a byte or a character. When a program tries to read past the end of the file, read() returns -1. If the return value from read() is not -1, you can cast the integer value to a byte or char or whatever...
So a program to read a file a character at a time could go like this:
Code java:
byte readingBytes[] = new byte[24];
int inputValue = 0;
int i = 0;
while ((inputValue != -1) && (i < readingBytes.length))
{
// Try{} Catch() is a good idea here, but I'll simplify...
inputValue = inputStream.read();
if (inputValue >= 0)
{
// Store inputValue in readingBytes[i] or whatever...
// For debugging:
// Make the program tell you exactly what it is seeing at each step!
System.out.printf("i = %d, inputValue = %d (0x%02x)\n",
i, inputValue, inputValue);
++i;
}
}
System.out.printf("Number of characters read = %d\n", i);
Quote:
Originally Posted by unCrypticSolutions
The file that I'm trying to open has the numbers 0 to 25 in it with no space or lines in between...
Hmmm. The plot thickens.
OK, suppose you are now able to read all of the characters in the file.
How do you know where one number ends and another begins?
I mean, suppose the file contains 12121.
Is this 1, 2, 1, 2, 1?
Or is it 1, 2, 1, 21?
Or is it 1, 2, 12, 1?
Or is it 12, 1, 21?
.
.
.
.
Or what???
Cheers!
Z
Re: Converting Bytes into Char
Short -> Char provides a bigger selection of characters