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エンコーディングをどこに置くべきか考えている人はいますか?

4

2 に答える 2

5

投稿したコードから、ストリームを「コピー」しようとしているのではなく、文字列に読み込んでいます。

コンストラクターでエンコーディングを指定するStringだけです。

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

個人的には、メソッド全体をGuava メソッドFiles.toString()の呼び出しに置き換えるだけです。

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

Java 6 以前を使用している場合は、 (Java 7 でのみ導入された)代わりにGuava フィールドCharsets.ISO_8859_1を使用する必要があります。StandardCharsets.ISO_8859_1

ただし、「コピー」という用語を使用すると、結果を他のファイル (またはストリーム) に書き込むことを示唆しています。それが true の場合byte[]、を直接処理し、 との間の (不要な) 変換を回避できるため、エンコーディングをまったく気にする必要はありませんString

于 2013-11-05T14:33:11.133 に答える
1

バイトを文字列に変換する場所、s = new String(bytes, encoding);またはその逆。

于 2013-11-05T14:36:10.263 に答える