将输入流转换为字符串的一种巧妙方法是使用 Scanner 对象
package org.wjw.mongo;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.Scanner;
public class InputToStringUtil {
private InputToStringUtil() {
}
public static String convertInputStreamToString(InputStream inputStream) {
try (Scanner scanner = new Scanner(inputStream).useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
public static String convertReaderToString(Reader reader) {
try (Scanner scanner = new Scanner(reader).useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
public static String convertFileToString(File file, Charset charset) throws IOException {
try (Scanner scanner = new Scanner(file, charset).useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
public static String convertPathToString(Path path, Charset charset) throws IOException {
try (Scanner scanner = new Scanner(path, charset).useDelimiter("\\A")) {
return scanner.hasNext() ? scanner.next() : "";
}
}
}
上面例子中,我们将通过将 InputStream
传递给其构造函数来创建 Scanner
对象。然后我们使用 useDelimiter()
方法将分隔符设置为 \\A
,这是一个与输入开头匹配的正则表达式。这会告知扫描程序将整个输入流作为单个令牌读取。最后,我们将令牌作为字符串返回。
<<<<<< [完] >>>>>>