Java字符串进阶

前言

String

构造

常用方法

注意


/*
* InputStreamReader实现了将字节流FileInputStream转换为字符流,然后使用转换来的字节流创建高效流,从而实现高效的读写
*/ /*
* 编码集(我的eclipse编辑器默认的是utf-8
* 下面将中文字符串的编码集变为GBK写入a.txt文件,因为a.txt默认的是utf-8的因此这里在文件中显示的是乱码
* 然后我们读出来的还是GBK的,因为我们写入的是GBK编码集的,但是我的eclipse是utf-8的编码集,因此在控制台上输出的还是乱码
* new String(byte[] bys,String
* charsetName)使用这个构造方法将byte数组改变编码集并且转换为utf-8格式的,那么这次在控制台上输出的就不乱码了
*/ // 将GBK格式的中文写入a.txt文件
File file = new File("src/a.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file);
String str = "中";
byte[] by = str.getBytes("GBK"); // 将字符串改为GBK编码集
fileOutputStream.write(by);
fileOutputStream.close(); //从a.txt文件中读取中文
FileInputStream fileInputStream = new FileInputStream(file);
int len;
byte[] bys = new byte[4];
while ((len = fileInputStream.read(bys)) != -1) {
System.out.println(new String(bys, "GBK"));
}
fileInputStream.close();

StringBuffer

    public synchronized StringBuffer append(Object obj) {
super.append(String.valueOf(obj));
return this;
} public synchronized StringBuffer append(String str) {
super.append(str);
return this;
} public synchronized StringBuffer delete(int start, int end) {
super.delete(start, end);
return this;
} /**
* @throws StringIndexOutOfBoundsException {@inheritDoc}
* @since 1.2
*/
public synchronized StringBuffer deleteCharAt(int index) {
super.deleteCharAt(index);
return this;
}

构造

常用的方法

StringBuilder

构造方法

常用方法

04-25 07:50