2015-11-30 78 views
0

我嘗試讀取文件到字符串,我試圖使編碼爲UTF-8,但仍然失敗,它會返回輸出中的一些奇怪的字符。奇怪的字符當從文本中讀取srt文件

這裏是我的功能來讀取文件:

private static String readFile(String path, boolean isRaw) throws UnsupportedEncodingException, FileNotFoundException{ 
    File fileDir = new File(path); 
try{  
    BufferedReader in = new BufferedReader(
     new InputStreamReader(
        new FileInputStream(fileDir), "UTF-8")); 

    String str; 

    while ((str = in.readLine()) != null) { 
     System.out.println(str); 
    } 

      in.close(); 
      return str; 
    } 
    catch (UnsupportedEncodingException e) 
    { 
     System.out.println(e.getMessage()); 
    } 
    catch (IOException e) 
    { 
     System.out.println(e.getMessage()); 
    } 
    catch (Exception e) 
    { 
     System.out.println(e.getMessage()); 
    } 
    return null; 
} 

第一線的輸出是:1

這裏是我的測試文件https://www.dropbox.com/s/2linqmdoni77e5b/How.to.Get.Away.with.Murder.S01E01.720p.HDTV.X264-DIMENSION.srt?dl=0

在此先感謝。

+0

您的CLI可能不支持Unicode字符集,可能會產生 –

+0

如果只有1個文件,在'記事本打開它++'並將它轉換成'UTF-8'並處理它,你正在做的 – Valijon

回答

3

該文件以UTF16-LE編碼,並有Byte order mark這有助於確定編碼。使用"UTF-16LE"字符集(或StandardCharsets.UTF_16LE)並跳過文件的第一個字符(例如,在第一行調用str.substring(1))。

+0

謝謝,它解決了我的問題,但我不需要刪除文件的第一個字符。嘗試調試並查看結果是否正常。 –

1

它看起來像您的文件編碼爲BOM文件。如果沒有需要處理BOM字符,然後打開記事本+ +和你的文件編碼爲UTF-8無BOM

要處理Java中的BOM文件,看看這個apache site for BOMInputStream

例子:

private static String readFile(String path, boolean isRaw) throws UnsupportedEncodingException, FileNotFoundException{ 
File fileDir = new File(path); 

try{ 
    BOMInputStream bomIn = new BOMInputStream(new FileInputStream(fileDir), ByteOrderMark.UTF_16LE); 

    //You can also detect UTF-8, UTF-16BE, UTF-32LE, UTF-32BE by using this below constructure 
    //BOMInputStream bomIn = new BOMInputStream(new FileInputStream(fileDir), ByteOrderMark.UTF_16LE, 
    //  ByteOrderMark.UTF_16BE, ByteOrderMark.UTF_32LE, ByteOrderMark.UTF_32BE, ByteOrderMark.UTF_8); 

    if(bomIn.hasBOM()){ 
     System.out.println("Input file was encoded as a bom file, the bom character has been removed"); 
    } 

    BufferedReader in = new BufferedReader(
     new InputStreamReader(
        bomIn, "UTF-8")); 

    String str; 

    while ((str = in.readLine()) != null) { 
     System.out.println(str); 
    } 

    in.close(); 
    return str; 
} 
catch (UnsupportedEncodingException e) 
{ 
    System.out.println(e.getMessage()); 
} 
catch (IOException e) 
{ 
    System.out.println(e.getMessage()); 
} 
catch (Exception e) 
{ 
    System.out.println(e.getMessage()); 
} 
return null; 
} 
+0

是的,問題是我需要使用字符集「UTF-16LE」像@Tagir Valeev的答案。謝謝! –

+0

是的,但不要刪除文件的第一個字符,如果它是一個bom文件。有一天,你想使用一個非Bom文件,然後你將最終刪除你想要在那裏的字符。將bom文件視爲bom文件,因此bominputstream非常方便 –

+0

我試過BOMInputStream,但看起來不工作,bomIn.hasBOM()即使演示文件也會返回false。有什麼方法可以檢測物料清單嗎? –

相關問題