【问题标题】:Read file path from utf-8 text file?从 utf-8 文本文件中读取文件路径?
【发布时间】:2011-10-16 17:36:32
【问题描述】:

我有一个 UTF-8 文本文件 example.txt,其中包含: c:/temp/file.txt

我使用这种方法读取文件内容:

public static String fileToString(final File file, final String charset) throws AppServerException
    {
        final byte[] buffer = new byte[(int) file.length()];
        FileInputStream fileInputStream = null;
        try
        {
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(buffer);
        }
        catch (final FileNotFoundException e)
        {
            throw new AppServerException(e.getMessage());
        }
        catch (final IOException e)
        {
            throw new AppServerException(e.getMessage());
        }
        finally
        {
            FileHelper.close(fileInputStream);
        }

        try
        {
            return new String(buffer,charset);
        }
        catch (UnsupportedEncodingException e)
        {
                throw new AppServerException(e.getMessage());
        }

    }

那我要检查c:/temp/file.txt这个文件是否存在:

String content = fileToString("example.txt","UTF8");
File file = new File(content );
System.out.println(file.exists());

exits() 返回 false 但文件确实存在。

如果我使用 notepad++ 将 example.txt 的编码更改为 ANSI,exists() 返回 true。

我已经尝试过使用: "c:\temp\file.txt", "c:\\temp\\file.txt", "c:\\\\temp\\\\file.txt", 但没有成功。

我确实需要将该文件用作 UTF8。你有提示让方法 exists() 返回 true 吗?

【问题讨论】:

    标签: java utf-8 filepath backslash


    【解决方案1】:

    Notepad++ 可能会在文件前面放置一个Byte Order Mark。这对于 UTF-8 和 Java does not interpret this sequence of three characters 是不必要的。

    如果您的文件名不包含任何非 ASCII 字符,请使用不使用字节顺序标记的编辑器或将字符串写入 ANSI。

    【讨论】:

    • Notepad++ 在选择 UTF-8 时确实有 BOM 选项。但是,我没有选择它:(。问题是该文件包含其他数据并且需要在 UTF8 中...
    • 您在问题中没有提到“其他数据”。难道问题实际上与其他数据有关?
    【解决方案2】:

    也许该文件实际上并未编码为 UTF-8。你能打印文件中“\”字符的实际字节值吗?

    当您使用它时:InputStream.read(byte[] b)保证从流中读取 b.length 字节。您应该循环读取并检查 read() 方法的返回值,以查看每次调用中实际读取了多少字节。

    【讨论】:

    • 文件采用 UTF-8 编码。使用调试路径是 "pretty": "c:/temp/file.txt" -> "c:/temp/file.txt"; “c:\temp\file.txt”->“c:\\temp\\file.txt”。但是 exists() 方法总是返回 false。同样使用调试,斜杠的实际字节值返回是 92。它似乎是正确的...... :(
    • 如果您创建传递文字字符串的 File 对象,而不是从文件中读取它,exist() 是否返回 true?
    • 是的,传递文件存在的文字。我做了这个“hack”:new String(content.getBytes(),"ASCII").substring(3);。转换为 ASCII,前 3 个字符是“垃圾”。这样做,它的工作原理......但我相信这不是最好的方法。但是,目前它可以工作。
    • 这肯定看起来像一个字节顺序标记。你能打印出前三个字符的值吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2012-01-05
    • 1970-01-01
    • 1970-01-01
    • 2011-08-03
    相关资源
    最近更新 更多