java中文字符串的处理_Java字符串处理技巧

  • Post author:
  • Post category:java


1. 鲜为人知的replaceAll技巧

System.out.println(“foo[0]”.replaceAll(“\\[(\\d+)\\]”, “.$1”));

//输出: foo.0

2. 构建一个重复的字符串

System.out.println(new String(new char[3]).replace(“\0”, “osc”));

//输出: oscoscosc

3. 按行读取字符串

BufferedReader br = new BufferedReader(new StringReader(“osc1\r\nosc2\r\nosc3”));

System.out.println(br.readLine());

System.out.println(br.readLine());

//输出:

//osc1

//osc2

4. 以指定编码从文件读取

BufferedReader reader =new BufferedReader(new InputStreamReader(new FileInputStream(“/home/joymufeng/file.txt”),”UTF-8″));

reader.readLine();

5. 以指定编码写入文件

Writer writer = new OutputStreamWriter(new FileOutputStream(“/home/joymufeng/file.txt”), “UTF-8”)

writer.write(“我是字符串!”);

writer.flush();

writer.close();

也可以使用PrintWriter:

PrintWriter out = new PrintWriter(“/home/joymufeng/file.txt”, “UTF-8”);

out.print(true);

out.print(3.14);

out.printf(“%d + %d = %d”.format(1, 1, 2));

out.println(“我是字符串”);

out.flush();

out.close();

6. 输出汉字的特定字符集编码

String code = new BigInteger(1, “你好”.getBytes(“utf-8”)).toString(16);

System.out.println(code);

输出:

e4bda0e5a5bd



版权声明:本文为weixin_39755824原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。