import java.io.FileWriter;
import java.io.IOException;
/*
* 演示字符输出流
*/
public class Demo04 {
public static void main(String[] args) throws IOException {
// 创建字符输入流对象
FileWriter fw = new FileWriter("a.txt");
fw.write("abc");
fw.write("你好");
fw.flush();
fw.close();
}
}
import java.io.FileReader;
import java.io.IOException;
/*
* 演示字符输入流
*/
public class Demo05 {
public static void main(String[] args) throws IOException {
// 创建输入流对象
FileReader fr = new FileReader("a.txt");
char[] ch = new char[1024];
int len = 0;
while ((len = fr.read(ch)) != -1) {
System.out.println(new String(ch, 0, len));
}
fr.close();
}
}
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
/*
* 使用字符流复制文件
*/
public class Demo06 {
@Test
public void test() throws IOException {
//创建字符输入输出流
FileReader fr = new FileReader("d:\\Demo3.java");
FileWriter fw = new FileWriter("d:\\复制.java");
char [] ch = new char [1024];
int len = 0 ;
while((len = fr.read(ch)) != -1) {
fw.write(ch,0,len);
fw.flush();
}
fr.close();
fw.close();
}
}
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
/*
* 编码、解码、乱码
*/
public class Demo07 {
public static void main(String[] args) throws IOException {
// 准备好被编码的数据
String s = "你好";
// 编码
byte[] by = s.getBytes("utf-8");
// 解码
String str = new String(by, "gbk");
System.out.println(str);
// 使用不一直的编码表导致乱码,
// 使用gbk反编ma
byte[] by2 = str.getBytes("gbk");
// 使用utf-8进行解码
String str2 = new String(by2, "utf-8");
System.out.println(str2);
//使用URLEncoder编码,使用URLDecoder解码
String str3 = URLEncoder.encode(s,"gbk");
String str4 = URLDecoder.decode(str3,"gbk");
System.out.println(str3);
System.out.println(str4);
}
}
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/592cfdd002c049633739c7a73b7127f6.png)
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import org.junit.Test;
/*
* 使用字符缓冲流复制文件
*/
public class Demo {
@Test
public void test() throws IOException {
FileReader fr = new FileReader("d:\\Demo3.java");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("d:复制.java");
BufferedWriter bw = new BufferedWriter(fw);
String line = null;
while((line =br.readLine()) != null ) {
bw.write(line);
bw.newLine();
}
br.close();
bw.close();
}
}