【发布时间】:2020-12-30 11:27:47
【问题描述】:
我班上的其他学生已经使用此代码,但我收到了一个错误。我正在尝试使用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;
}
}
}
【问题讨论】:
-
readAllBytes()在 Java9 中定义。确保使用正确的 java 版本(编译器和 JRE)。 -
您应该尝试发布minimal reproducible example。您要读取哪种文件?是文本文件吗?就像您从 IDE 复制 Java 代码并将其作为文本粘贴到问题中一样,您应该对错误消息执行相同操作。您不应发布错误消息的图片。
-
也许您可以发布一个您正在尝试阅读的示例文件?
-
请标记第 39 行,因为我们看不到它。
标签: java data-stream