1.体系图解
2.代码
2.1 字符流读取文件
package com.fjh;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class CharStream {
public static void main(String[] args) throws IOException {
//System.getProperty("user.dir")读取用户当前工作环境目录
File file = new File(System.getProperty("user.dir")+"/1.txt");
if(!file.exists()){
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//字符流
Reader read = new FileReader(file);
//读内容
char[] cbuf = new char[1024];//每次读取的字符数
int len = 0;
String content = null;
//将字节数组转化为字符串
while((len = read.read(cbuf)) != -1){//返回-1代表的是已经读取完毕
content =new String(cbuf, 0, len);
}
System.out.println("读取的内容为:"+content);
if(null != read){
read.close();
}
}
}
package com.fjh;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Reader;
public class BufferReaderStream {
public static void main(String[] args) throws IOException {
File file = new File(System.getProperty("user.dir") + "/1.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Reader read = new FileReader(file);
BufferedReader bf = new BufferedReader(read);
String str = null;
while ((str = bf.readLine()) != null){
System.out.println(str);
}
bf.close();
}
}
2.2 字节流读取文件,字符流写入文件
package com.fjh;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Writer;
public class ByteStream {
public static void main(String[] args) throws IOException {
File file = new File(System.getProperty("user.dir") + "/1.txt");
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 字节流
InputStream is = new FileInputStream(file);
// 读内容,按字节读取
byte[] b = new byte[1024];// 每次读取的字节数
int len = 0;
String content = null;
// 将字节数组转化为字符串
while ((len = is.read(b)) != -1) {// 返回-1代表的是已经读取完毕
content = new String(b, 0, len);
}
System.out.println("读取的内容为:" + content);
if (null != is) {
is.close();
}
// 字节流写入文件
File file2 = new File(System.getProperty("user.dir") + "/2.txt");
if (!file2.exists()) {
try {
file2.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
OutputStream os = new FileOutputStream(file2);
String str = "fsdf看发生";
os.write(str.getBytes());
os.close();
// 字符流写入内容
Writer write = new FileWriter(file2, true);// true表示从文件后面接着写入
String str2 = "发生纠纷好看fsdaf";
write.write(str2);
// 关闭
write.close();
}
}