【问题标题】:Encoding of forward slash ('\u002f') in Java stringsJava 字符串中正斜杠 ('\u002f') 的编码
【发布时间】:2015-11-19 09:41:15
【问题描述】:

我在 Java 中对正斜杠字符进行编码时遇到问题。我有这个程序来说明正在发生的事情 -

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.charset.Charset;

import org.apache.commons.io.IOUtils;

public class SlashTester {

    public static void main(String[] args) throws FileNotFoundException, IOException {
        String input = "http:\u002f\u002fgoogle.com";
        System.out.println(input); // Prints "http://google.com"

        String input2 = IOUtils.toString(new FileInputStream("hello.txt"), Charset.forName("UTF-8"));
        System.out.println(input2); //Prints "http:\u002f\u002fgoogle.com"
    }
}

程序从文件“hello.txt”中读取。该文件的内容只是 -

http:\u002f\u002fgoogle.com

请注意,这与字符串 'input' 相同。

谁能向我解释为什么输出会有所不同?

【问题讨论】:

    标签: java string utf-8 character-encoding


    【解决方案1】:

    Java 编译器理解\uXXXX 语法并翻译这些字符。如果您想执行此翻译,您需要自己执行此操作。

    注意:这甚至不必在字符串中,您可以执行以下操作

    \u0053\u0079\u0073\u0074\u0065\u006d\u002e\u006f\u0075\u0074\u002e\u0070\u0072\u0069\u006e\u0074\u006c\u006e\u0028\u0022\u0028\u0022\u006 u006c\u006f\u0020\u0057\u006f\u0072\u006c\u0064\u0022\u0029\u003b

    相同
    System.out.println("Hello World");
    

    因为编译器会在检查代码之前翻译这些字符。

    【讨论】:

    • 谢谢。这就解释了!我反编译了.class文件,发现字符串只是"http://google.com"
    • @MediumOne 修复此字符的一种粗略方法是 input2 = input2.replaceAll("\\\\u002f", "/");
    【解决方案2】:

    你必须给你的String加上双重反冲以避免这种行为,因为:

    String input = "http:\\u002f\\u002fgoogle.com";
    

    它将打印您http:\u002f\u002fgoogle.com。这是因为在 String 中,特殊字符必须在它们之前用反冲符号 \ 进行转义。

    有关更多信息,您可以查看:javadocs

    希望对你有帮助!

    【讨论】:

      【解决方案3】:

      适用于任何想要将 unicode url 或字符串转换并转义为未转义的人 和我一样

      转义字符:

      'http\\u00253A\\u00252F\\u00252Fexample.com';
      

      非转义字符:

      'http://example.com'
      

      使用这个技巧可以节省你的时间(from radicant's answer):

      decodeURIComponent(JSON.parse('"http\\u00253A\\u00252F\\u00252Fexample.com"'));
      > 'http://example.com'
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-02-27
        • 2011-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多