带有 ISO-8859-1 的 Java 快速流复制

标签 java iso-8859-1

我有以下代码,它将读取 ISO-8859-1 中的文件,因为这就是此应用程序所需要的,

private static String readFile(String filename) throws IOException {




String lineSep = System.getProperty("line.separator");
File f = new File(filename);
StringBuffer sb = new StringBuffer();
if (f.exists()) {
 BufferedReader br =
 new BufferedReader(
   new InputStreamReader(
              new FileInputStream(filename), "ISO-8859-1"));

 String nextLine = "";
 while ((nextLine = br.readLine()) != null) {
   sb.append(nextLine+ " ");
   // note:  BufferedReader strips the EOL character.
  // sb.append(lineSep);
 }
  br.close();
}

return sb.toString();
}

问题是它很慢。我有这个功能,速度更快,但我似乎无法找到如何放置字符编码:

private static String fastStreamCopy(String filename)
{
   String s = "";
FileChannel fc = null;
try
{
    fc = new FileInputStream(filename).getChannel();



    MappedByteBuffer byteBuffer = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());

    int size = byteBuffer.capacity();
    if (size > 0)
        {

            byteBuffer.clear();
            byte[] bytes = new byte[size];
            byteBuffer.get(bytes, 0, bytes.length);
            s = new String(bytes);
        }

        fc.close();
    }
    catch (FileNotFoundException fnfx)
    {

        System.out.println("File not found: " + fnfx);
    }
    catch (IOException iox)
{

    System.out.println("I/O problems: " + iox);
   }
finally
    {
    if (fc != null)
        {
        try
            {
            fc.close();
            }
        catch (IOException ignore)
        {

        }
    }
    }
   return s;
}

有人知道我应该把 ISO 编码放在哪里吗?

最佳答案

从您发布的代码来看,您并不是要“复制”流,而是要将其读入字符串。

您可以简单地在 the String constructor 中提供编码:

s = new String(bytes, "ISO-88591-1");

我个人只是将整个方法替换为对 Guava 的调用method Files.toString() :

String content = Files.toString(new File(filename), StandardCharsets.ISO_8859_1);

如果您使用的是 Java 6 或更早版本,则需要使用 Guava 字段 Charsets.ISO_8859_1而不是 StandardCharsets.ISO_8859_1 (仅在 Java 7 中引入)。

但是您对术语“复制”的使用表明您希望将结果写入其他文件(或流)。 如果这是真的,那么您根本不需要关心编码,因为您可以直接处理 byte[] 并避免(不必要的)转换往返于 String

关于带有 ISO-8859-1 的 Java 快速流复制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19791343/

相关文章:

java - ApacheDS - 自定义搜索处理程序 (Java)

php - 浏览器如何覆盖我的 UTF-8 header 设置以及如何停止它?

sql - cfquery 文本编码问题

java - Java MicroEdition 中的 XML 数据绑定(bind)

2 毫秒精度的 Java DateFormat

java - 名称未找到异常 : While trying to lookup 'jdbc' only when publishing from Eclipse Kepler but not Indigo

java - 时间触发作业 Cron 或 Quartz?

java - 特殊字符如 ?在 SMPP 和 Java 中

email - 使用 EWS API 发送电子邮件时控制消息编码

html - 一个 HTML 页面中的多个字符编码可能吗?