假设我刚刚使用 BufferedInputStream
将 UTF-8 编码文本文件的字节读入字节数组。我知道我可以使用以下例程将字节转换为字符串,但是是否有比仅遍历字节并转换每个字节更有效/更智能的方法呢?
public String openFileToString(byte[] _bytes)
{
String file_string = "";
for(int i = 0; i < _bytes.length; i++)
{
file_string += (char)_bytes[i];
}
return file_string;
}
String fileString = new String(_bytes,"UTF-8");
?
查看 String 的构造函数
String str = new String(bytes, StandardCharsets.UTF_8);
如果您觉得懒惰,可以使用 Apache Commons IO 库将 InputStream 直接转换为字符串:
String str = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
Java String 类具有用于将字节数组转换为字符串的内置构造函数。
byte[] byteArray = new byte[] {87, 79, 87, 46, 46, 46};
String value = new String(byteArray, "UTF-8");
要转换 utf-8 数据,不能假设字节和字符之间存在 1-1 对应关系。尝试这个:
String file_string = new String(bytes, "UTF-8");
(呸。我发现我在点击“发布您的答案”按钮时速度变慢了。)
要将整个文件作为字符串读取,请执行以下操作:
public String openFileToString(String fileName) throws IOException
{
InputStream is = new BufferedInputStream(new FileInputStream(fileName));
try {
InputStreamReader rdr = new InputStreamReader(is, "UTF-8");
StringBuilder contents = new StringBuilder();
char[] buff = new char[4096];
int len = rdr.read(buff);
while (len >= 0) {
contents.append(buff, 0, len);
}
return buff.toString();
} finally {
try {
is.close();
} catch (Exception e) {
// log error in closing the file
}
}
}
您可以为此使用 String(byte[] bytes)
构造函数。有关详细信息,请参阅此 link。 编辑您还必须根据 java 文档考虑您的平台的默认字符集:
通过使用平台的默认字符集解码指定的字节数组来构造一个新的字符串。新字符串的长度是字符集的函数,因此可能不等于字节数组的长度。当给定字节在默认字符集中无效时,此构造函数的行为未指定。当需要对解码过程进行更多控制时,应使用 CharsetDecoder 类。
Charset
参数的版本来确保转换正确。
您可以使用此问题中描述的方法(特别是因为您从 InputStream 开始):Read/convert an InputStream to a String
特别是,如果您不想依赖外部库,您可以尝试 this answer,它通过 InputStreamReader
将 InputStream
读入 char[]
缓冲区并将其附加到 StringBuilder
。
知道您正在处理一个 UTF-8 字节数组,您肯定会想要使用 String constructor that accepts a charset name。否则,您可能会面临一些基于字符集编码的安全漏洞。请注意,它会抛出您必须处理的 UnsupportedEncodingException
。像这样的东西:
public String openFileToString(String fileName) {
String file_string;
try {
file_string = new String(_bytes, "UTF-8");
} catch (UnsupportedEncodingException e) {
// this should never happen because "UTF-8" is hard-coded.
throw new IllegalStateException(e);
}
return file_string;
}
这是一个以字节为单位读取并创建字符串的简化函数。它假定您可能已经知道文件的编码方式(否则为默认值)。
static final int BUFF_SIZE = 2048;
static final String DEFAULT_ENCODING = "utf-8";
public static String readFileToString(String filePath, String encoding) throws IOException {
if (encoding == null || encoding.length() == 0)
encoding = DEFAULT_ENCODING;
StringBuffer content = new StringBuffer();
FileInputStream fis = new FileInputStream(new File(filePath));
byte[] buffer = new byte[BUFF_SIZE];
int bytesRead = 0;
while ((bytesRead = fis.read(buffer)) != -1)
content.append(new String(buffer, 0, bytesRead, encoding));
fis.close();
return content.toString();
}
String 有一个以 byte[] 和 charsetname 作为参数的构造函数:)
这也涉及迭代,但这比连接字符串要好得多,因为它们非常昂贵。
public String openFileToString(String fileName)
{
StringBuilder s = new StringBuilder(_bytes.length);
for(int i = 0; i < _bytes.length; i++)
{
s.append((char)_bytes[i]);
}
return s.toString();
}
String str = new String(byte[])
会很好。
为什么不从一开始就得到你正在寻找的东西并从文件中读取一个字符串而不是一个字节数组?就像是:
BufferedReader in = new BufferedReader(new InputStreamReader( new FileInputStream( "foo.txt"), Charset.forName( "UTF-8"));
然后从 in 开始 readLine 直到完成。
我用这种方式
String strIn = new String(_bytes, 0, numBytes);
不定期副业成功案例分享
java.nio.charset.Charset.availableCharsets()
映射所有字符集,而不仅仅是StandardCharsets
中的字符集。如果您想使用其他字符集并且仍想阻止 String 构造函数抛出UnsupportedEncodingException
,您可以使用java.nio.charset.Charset.forName()