问题描述
我班上的其他学生已经使用了此代码,但出现错误。我正在尝试使用readAllBytes()
方法进行分配,但无法正常工作。我的老师还有另一种他打算使用该方法的方式:未为DataInputStream
定义该方法。
看一下read(byte[])
方法,数据流中的第一个整数显示字节数组的大小。无论哪种方式都可以,我只是在第39行出现错误,并且如果我删除“ import java.io.DataInputStream;”,它修复了该错误,但在第31行却出现了错误。任何帮助将不胜感激enter image description here
package edu.ics211.h03;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.io.InputStream;
/**
* Represents a ReadFile.
*
* @author Constantine Peros
*/
public class ReadFile implements IReadFile {
/**
* Creates a New ReadFile.
*/
public ReadFile() {
// Todo Auto-generated constructor stub
}
@Override
public String readFile(String fileName) throws IOException {
// Create a FileInputStream from the file name
// Create a DataInputStream from the FileInputStream
DataInputStream data = new DataInputStream(new FileInputStream(fileName));
// Read the number of bytes using readInt
int size = data.readInt();
// Read the encoding using readByte
byte encoding = data.readByte();
// Create a byte array number of bytes long
byte[] byteArray = new byte[size];
// Fill the byte array
byteArray = data.readAllBytes();
// Close my inputs
data.close();
// Switch the encoding or use if statements
switch (encoding) {
case 1:
return new String(byteArray,StandardCharsets.US_ASCII);
break;
case 2:
return new String(byteArray,StandardCharsets.UTF_16LE);
break;
case 3:
return new String(byteArray,StandardCharsets.UTF_8);
break;
case 4:
return new String(byteArray,StandardCharsets.UTF_16);
break;
default:
return null;
}
}
}
解决方法
在我看来,您需要做的就是替换这段代码
byteArray = data.readAllBytes();
与此行
data.read(byteArray);
这是整个方法。
public String readFile(String fileName) throws IOException {
// Create a FileInputStream from the file name
// Create a DataInputStream from the FileInputStream
DataInputStream data = new DataInputStream(new FileInputStream(fileName));
// Read the number of bytes using readInt
int size = data.readInt();
// Read the encoding using readByte
byte encoding = data.readByte();
// Create a byte array number of bytes long
byte[] byteArray = new byte[size];
// Fill the byte array
data.read(byteArray);
// byteArray = data.readAllBytes();
// Close my inputs
data.close();
// Switch the encoding or use if statements
switch (encoding) {
case 1:
return new String(byteArray,StandardCharsets.US_ASCII);
case 2:
return new String(byteArray,StandardCharsets.UTF_16LE);
case 3:
return new String(byteArray,StandardCharsets.UTF_8);
case 4:
return new String(byteArray,StandardCharsets.UTF_16);
default:
return null;
}
}