2

可能重复:
字节顺序标记搞砸了 Java 中的文件读取

public Collection<String> getLines(String path) throws SftpException
{
   BufferedReader reader = null;
   try
   {
      reader = new BufferedReader(new InputStreamReader(get(path)));

      Collection<String> result = new ArrayList<String>();
      String line;
      while((line = reader.readLine()) != null)
      {
         result.add(line);
      }
      return result;
   }
   catch (IOException e)
   {
      throw new SftpException("Could not get lines from '"+path+"'.", e);
   }
   finally
   {
      if(reader != null)
         try
         {
            reader.close();
         }
         catch (IOException e)
         {
            throw new SftpException("Failed to close stream", e);
         }
   }
}

我使用上述方法获取位于 SFTP 服务器上的文件中的所有行。该get(path)方法将文件内容作为InputStream. 在我的特殊情况下,该文件是一个包含多个分组订单的 CSV。要检查一行是订单还是新组的标题,我会使用line.startsWith("HDR").

我的问题是我突然发现我的代码跳过了第一行。当我进入调试器时,我发现我的集合中的第一行实际上在HDR部件之前有一些奇怪的字符。我怀疑它是 UTF-8 BOM 或类似的东西。那么,我该如何处理呢?如何正确读取 UTF-8 文件?有没有办法检查它是否真的是 UTF-8 文件?


更新:在 Byte order mark 中找到了一个解决方案,搞砸了 Java 中的文件读取,所以关闭它:)

4

0 回答 0