使用ISO-8859-1进行Java快速流复制

时间:2013-11-05 14:30:23

标签: 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编码放在哪里?

2 个答案:

答案 0 :(得分:5)

根据您发布的代码,您不是要“复制”流,而是将其读取为字符串。

您只需在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[]并避免({不必要的)转换为{{ 1}}。

答案 1 :(得分:1)

您要将字节转换为字符串,例如s = new String(bytes, encoding);,反之亦然。

相关问题