我看了一些以前关于二进制文件的线程,我正在像说的那样执行dataStream,但是我不确定为什么我的行不通,因为我认为我做的事情与线程说的一样。我的目标是制作一种方法,该方法采用.bin格式的文件名,并带有一个移位整数。我将创建一个.bin类型的新文件,其中的字符已转换。不过,只有大写或小写字母会转移。我不知道正在读取的二进制文件的长度,并且需要检查所有字符。该文件只有1行。我有一种方法可以让我在那一行上显示字符数,并且可以创建一个文件。我知道的程序确实可以正确创建文件。无论如何,正在发生的事情是它创建了文件,然后给我关于该行的EOF异常:char currentChar = data.readChar();
这是我的代码:
private static void cipherShifter(String file, int shift) {
String newFile=file+"_cipher";
createFile(newFile);
int numChar;
try {
FileInputStream stream=new FileInputStream(file);
DataInputStream data=new DataInputStream(stream);
FileOutputStream streamOut=new FileOutputStream(newFile);
DataOutputStream dataOut=new DataOutputStream(streamOut);
numChar=readAllInts(data);
for (int i=0;i<numChar;++i) {
char currentChar=data.readChar();
if (((currentChar>='A')&&(currentChar<='Z'))||((currentChar>='a')&&(currentChar<='z'))) {
currentChar=currentChar+=shift;
dataOut.writeChar(currentChar);
}
else {
dataOut.writeChar(currentChar);
}
}
data.close();
dataOut.flush();
dataOut.close();
} catch(IOException error) {
error.printStackTrace();
}
}
private static void createFile(String fileName) {
File file=new File(fileName);
if (file.exists()) {
//Do nothing
}
else {
try {
file.createNewFile();
} catch (IOException e) {
//Do nothing
}
}
}
private static int readAllInts(DataInputStream din) throws IOException {
int count = 0;
while (true) {
try {
din.readInt(); ++count;
} catch (EOFException e) {
return count;
}
}
}
因此,我认为该错误不会发生,因为我确实具有正确的数据类型,并且告诉它仅读取一个字符。任何帮助都会很棒。提前致谢。
最佳答案
根据上面的描述,您的错误将在data.readChar()方法调用时报告,而不是在readAllInts方法内报告。我模拟了靠近您的错误的代码,并在同一位置的文本文件上得到了相同的异常。
因为您主要对ASCII字节感兴趣,所以我使用readByte方法一次读取一个字节。我也将readAllInts更改为readAllBytes,所以我使用总字节数。
private static void cipherShifter(String file, int shift) {
String newFile=file+"_cipher";
createFile(newFile);
int numChar;
try {
FileInputStream stream=new FileInputStream(file);
DataInputStream data=new DataInputStream(stream);
FileOutputStream streamOut=new FileOutputStream(newFile);
DataOutputStream dataOut=new DataOutputStream(streamOut);
numBytes=readAllBytes(data);
stream.close();
data.close();
stream=new FileInputStream(file);
data=new DataInputStream(stream);
for (int i=0;i<numBytes;++i) {
byte currentByte=data.readByte();
if (((currentByte>=65)&&(currentByte<=90))||((currentByte>=97)&&(currentByte<=122))) {
currentByte=currentByte+=shift; //need to ensure no overflow beyond a byte
dataOut.writeByte(currentByte);
}
else {
dataOut.writeByte(currentByte);
}
}
data.close();
dataOut.flush();
dataOut.close();
} catch(IOException error) {
error.printStackTrace();
}
}
private static void createFile(String fileName) {
File file=new File(fileName);
if (file.exists()) {
//Do nothing
}
else {
try {
file.createNewFile();
} catch (IOException e) {
//Do nothing
}
}
}
private static int readAllBytes(DataInputStream din) throws IOException {
int count = 0;
while (true) {
try {
din.readByte(); ++count;
} catch (EOFException e) {
return count;
}
}
}