IO(字符流)
public class CharSetDemo1 {
public static void main(String[] args) throws UnsupportedEncodingException {
/*
java编码方式:
byte[] getBytes() 使用默认方式编码
byte[] getBytes(String charsetName) 使用指定方式编码
java解码方式:
String(byte[] bytes) 使用默认方式解码
String(byte[] bytes,String charsetName) 使用指定方式解码
*/
//使用默认方式编码
String str="香香";
byte[] bytes = str.getBytes();
System.out.println(Arrays.toString(bytes));
//使用指定方式编码
byte[] bytes1=str.getBytes("GBK");//也可小写
System.out.println(Arrays.toString(bytes1));
//使用默认方式解码
String s=new String(bytes);
System.out.println(s);
//使用指定方式解码
String s1=new String(bytes1,"GBK");
System.out.println(s1);
}
}
-----------------------
public class CharStreamDemo1 {
public static void main(String[] args) throws IOException {
//读取FileReader
/*
方法与字节流相似
public int read(char[] chars) 读取多个数据,读到末尾返回-1
*/
FileReader fr=new FileReader("day31-code\\src\\a.txt");
int ch;
//读取中文时和字节流不同,字节流读取一个字节,中文会出现乱码,字符流读取一个字符,不会出现乱码
//空参的read方法
while((ch=fr.read())!=-1){
System.out.print((char)ch);
}
fr.close();
}
}
---------------------------------
public class CharStreamDemo2 {
public static void main(String[] args) throws IOException {
FileReader fr=new FileReader("day31-code\\src\\a.txt");
//带参数的read方法
char[] chars=new char[1024];
int len;
while((len=fr.read(chars))!=-1){
System.out.println(new String(chars,0,len));
}
fr.close();
}
}
-----------------------------
public class CharStreamDemo3 {
public static void main(String[] args) throws IOException {
//写出FileWriter
/*
void write(int c) 写入单个字符。
void write(String str) 写入字符串。
void write(String str, int off, int len) 写入字符串的某一部分。
void write(char[] cbuf) 写入字符数组。
void write(char[] cbuf, int off, int len) 写入字符数组的某一部分。
*/
//1.写入单个字符
FileWriter fw=new FileWriter("day31-code\\src\\a.txt",true);//
fw.write(65);
//2.写入字符串
fw.write("\r\n");//换行
fw.write("haha");
//3.写入字符串的某一部分
fw.write("\r\n");//换行
fw.write("aaabbb",3,3);//从索引3开始,写3个字符
//4.写入字符数组
fw.write("\r\n");//换行
char[] chars={'x','i','a','n','g','x','i','a','n','g'};
fw.write(chars);
//5.写入字符数组的某一部分
fw.write("\r\n");//换行
fw.write(chars,5,5);//从索引5开始,写5个字符
fw.close();
}
}
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Hexo!