我知道我能做到。但我也想知道,有没有一种捷径可以做到这一点?例如:为什么在 Reader
类层次结构中没有具有 public String readString(int len);
原型(prototype)的方法来仅使用此问题中的单个代码来完成我想要的操作?
InputStream in = new FileInputStream("abc.txt");
InputStreamReader inReader = new InputStreamReader(in);
char[] foo = new char[5];
inReader.read(foo);
System.out.println(new String(foo));
// I think this way is too long
// for reading a string that has only 5 character
// from InputStream or Reader
在Python 3编程语言中,我可以非常轻松地处理UTF-8和其他文件。考虑以下代码。
fl = open("abc.txt", mode="r", encoding="utf-8")
fl.read(1) # returns string that has 1 character
fl.read(3) # returns string that has 3 character
如何在 Java 中加点?
谢谢。
最佳答案
How can I do it in Java ?
您已经这样做的方式。
我建议使用可重用的辅助方法来完成此操作,例如
final class IOUtil {
public static String read(Reader in, int len) throws IOException {
char[] buf = new char[len];
int charsRead = in.read(buf);
return (charsRead == -1 ? null : new String(buf, 0, charsRead));
}
}
然后像这样使用它:
try (Reader in = Files.newBufferedReader(Paths.get("abc.txt"), StandardCharsets.UTF_8)) {
System.out.println(IOUtil.read(in, 5));
}
关于java - 从 InputStream 或 Reader 读取长度为 n 的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51089203/