1 字节流作业
public static void main(String[] args)throws Exception{
copy(new File("C:\\Users\\Administrator\\Desktop\\java43课堂记录"),
new File("C:\\Users\\Administrator\\Desktop\\aa"));
}
public static void fuZhi(File a,File b)throws Exception {
FileInputStream fin=new FileInputStream(a);
FileOutputStream fout=new FileOutputStream(b);
byte[] arr=new byte[1024];
int n;
while((n=fin.read(arr))!=-1) {
fout.write(arr, 0, n);
}
fin.close();
fout.close();
}
public static void copy(File yuan,File muDi)throws Exception{
if(!yuan.exists()) {
throw new RuntimeException(yuan.getAbsolutePath()+"不存在!");
}
if(!muDi.exists()) {
muDi.mkdirs();
}
File zi=new File(muDi,yuan.getName());
if(yuan.isFile()) {
zi.createNewFile();
fuZhi(yuan,zi);
return;
}
zi.mkdir();
File[] ziFiles=yuan.listFiles();
for (File ziFile : ziFiles) {
copy(ziFile,zi);
}
}
public static void cut(File yuan,File muDi)throws Exception{
if(!yuan.exists()) {
throw new RuntimeException(yuan.getAbsolutePath()+"不存在!");
}
if(!muDi.exists()) {
muDi.mkdirs();
}
File zi=new File(muDi,yuan.getName());
if(yuan.isFile()) {
zi.createNewFile();
fuZhi(yuan,zi);
System.out.println(yuan.getAbsolutePath()+"删除:::"+yuan.delete());
return;
}
zi.mkdir();
File[] ziFiles=yuan.listFiles();
for (File ziFile : ziFiles) {
cut(ziFile,zi);
}
System.out.println(yuan.getAbsolutePath()+"删除:::"+yuan.delete());
}
2 字符流
字符流:每次读写的是一个字符对应的多个字节
2.1 字符输入流
* FileReader:字符输入流
* 构造方法:
* FileReader(File file)
* FileReader(String fileName)
* 普通方法:
* void close() :关闭流释放资源
* String getEncoding() :获取编码集
* int read():每次读取一个字符 :::如果已到达流的末尾,则返回 -1
* int read(char[] arr):每次读取一个字符数组:::如果已到达流的末尾,则返回 -1
public static void testFileReader1()throws Exception {
FileReader fin=new FileReader("src/Test/2.txt");
int c;
while((c=fin.read())!=-1) {
System.out.print((char)(c));
}
fin.close();
}
public static void testFileReader2()throws Exception {
FileReader fin=new FileReader("src/Test/2.txt");
int n;
char[] arr=new char[10];
while((n=fin.read(arr))!=-1) {
System.out.print(new String(arr, 0, n));
}
System.out.println("获取编码集:::"+fin.getEncoding());
fin.close();
}
2.2 字符输出流
* FileWriter:字符输出流
* 构造方法:
* FileWriter(File file)
* FileWriter(String fileName)
* FileWriter(File file,boolean append)
* FileWriter(String fileName,boolean append)
* 普通方法:
* void close() :关闭流释放资源
* void write(int n);一次写一个字符
* void write(char[] arr);一次写一个字符数组
* void write(char[] arr,int startIndex,int length);一次写一个字符数组的一部分
* String getEncoding() :获取编码集
* void flush();
* ---注意1:
* FileOutPutStream的write方法:把字节信息直接写道目的文件中
* 其他输出流的write方法:是把信息写道缓存区中
* 其他输出流的flash方法:把缓存区中的信息刷新到目的文件中
*
* 所以:除了FileOutPutStream 其他所有的输出流 每次write之后都需要flash
*
* --注意2:
* 只有文本类型的文件 选择 使用字符流
* 所有文件都可以使用字节流
public static void testFileWriter()throws Exception {
FileWriter fout=new FileWriter("src/Test/3.txt");
fout.write('还');
fout.flush();
fout.write("你是吗?\r\n".toCharArray());
fout.flush();
fout.write("123abc你好吗?AAA".toCharArray(),3,5);
fout.flush();
}
2.3 字符流实现文件的复制
public static void copyByReaderWriter() throws Exception {
FileReader fin=new FileReader("src/Test/Demo01.java");
FileWriter fout=new FileWriter("src/Test/Demo01.txt");
char[] arr=new char[10];
int n;
while((n=fin.read(arr))!=-1) {
fout.write(arr, 0, n);
fout.flush();
}
fin.close();
fout.close();
}
3 高效流
3.1 概念和方法
* 高效流:Buffered 是过滤器(关联的是节流流 对节点流的功能进行加强)
* 读写速度比关联的节点流快
* 字节高效流:BufferedInputStream+BufferedOutputStream
* 除了输出流需要flush 没有特有方法 和FileInputStream+FileOutputStream
* 字符高效流:BufferedReader+BufferedWriter
* 特点:1 高效读写 2 支持逐行读写
* BufferedReader:
* 构造方法:
* BufferedReader(Reader in)
* 普通方法:
* int read()
* int read(char[] cbuf, int off, int len)
* int read(char[] cbuf)
* void close()
* 特有方法:
* String readLine() ;一次读取一行: 如果已到达流末尾,则返回 null
*BufferedWriter:
* 构造方法:
* BufferedWriter(Writer out)
* 普通方法:
* void close()
* void flush()
* void write(int c)
* void write(char[] cbuf, int off, int len)
* void write(char[] cbuf)
* void write(String message)
* void write(String s, int off, int len)
* 特有方法:
* void newLine()
3.2 高效字符流实现复制
public static void testBufferedReaderWriter()throws Exception{
FileReader fin=new FileReader("src/Test/Student.java");
FileWriter fout=new FileWriter("src/Test/Student.txt");
BufferedReader bin=new BufferedReader(fin);
BufferedWriter bout=new BufferedWriter(fout);
String line;
while((line=bin.readLine())!=null) {
bout.write(line);
bout.flush();
bout.newLine();
bout.flush();
}
bin.close();
bout.close();
}
3.3 高效字节流实现复制
public static void testBufferedStream()throws Exception{
FileInputStream fin=new FileInputStream("src/Test/55.jpeg");
FileOutputStream fout=new FileOutputStream("src/Test/555.jpeg");
BufferedInputStream bin=new BufferedInputStream(fin);
BufferedOutputStream bout=new BufferedOutputStream(fout);
byte[] arr=new byte[1024];
int n;
while((n=bin.read(arr))!=-1) {
bout.write(arr, 0, n);
bout.flush();
}
bin.close();
bout.close();
}
4 转换流
4.1 转换流概念
转换流--过滤流
转换流:把字节流转换为字符流
InputStreamReader 是字节输入流流通向字符输入流的桥梁
OutputStreamWriter 是字节输出流流通向字符输出流的桥梁
相当于FileReader和FileWriter没有特有方法: 但 OutputStreamWriter需要flush
构造方法:
OutputStreamWriter(OutputStream out, String charsetName)
InputStreamReader(InputStream in, String charsetName)
4.2转换流实现复制
public static void copy() throws Exception{
InputStreamReader in=new InputStreamReader(new FileInputStream("src/Test/Demo01.txt"),"GBK");
OutputStreamWriter out=new OutputStreamWriter(new FileOutputStream("src/Test/Demo02.txt"),"GBK");
char[] arr=new char[10];
int n;
while((n=in.read(arr))!=-1) {
out.write(arr, 0, n);
}
in.close();
out.close();
}
public static void change() throws Exception{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader bin=new BufferedReader(in);
String line;
while(true) {
line=bin.readLine();
if(line.endsWith("886")) {
break;
}
line=changeStr(line);
System.out.println("读取的信息是:::"+line);
}
}
private static String changeStr(String str) {
StringBuffer stb=new StringBuffer(str);
for (int i = 0; i < stb.length(); i++) {
char c=stb.charAt(i);
if(c>='a'&&c<='z') {
stb.setCharAt(i, (char)(c-('a'-'A')));
}else if(c>='A'&&c<='Z') {
stb.setCharAt(i, (char)(c+('a'-'A')));
}else if(c>='0'&&c<='9') {
stb.deleteCharAt(i);
i--;
}
}
return stb.toString();
}
5 练习
5.1 练习1
public static void main(String[] args) throws Exception {
yunSuan();
}
public static void yunSuan()throws Exception {
BufferedReader bin=new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bout=new BufferedWriter(new FileWriter("src/Test/运算.txt"));
String line;
while(true) {
line=bin.readLine();
if(line.endsWith("%886%")) {
break;
}
line=changeStr(line);
bout.write(line);
bout.flush();
bout.newLine();
bout.flush();
}
bout.close();
}
private static String changeStr(String line) {
line=line.trim();
int index=0;
if(line.contains("+")) {
index=line.indexOf("+");
}else if(line.contains("-")) {
index=line.indexOf("-");
}else if(line.contains("*")) {
index=line.indexOf("*");
}else if(line.contains("/")) {
index=line.indexOf("/");
}
char ysf=line.charAt(index);
double num1=Double.parseDouble(line.substring(0,index).trim());
double num2=Double.parseDouble(line.substring(index+1).trim());
double result=0;
switch(ysf) {
case '+':
result=num1+num2;
break;
case '-':
result=num1-num2;
break;
case '*':
result=num1*num2;
break;
case '/':
result=num1/num2;
break;
}
return num1+""+ysf+num2+"="+result;
}
5.2 练习2
public class LianXi02 {
public static void main(String[] args)throws Exception {
System.out.println("修改一个:"+IoUtil.updateOne(new Student(1002, "新来的", "妖", 11f, 12, true)));
System.out.println("获取所有::"+IoUtil.getAll());
}
}
class IoUtil{
private static final String filePath="src/day14_io/Student.txt";
public static int addOne(Student s)throws Exception {
writeString(s.toString()+"\r\n",true);
return 1;
}
public static Student getOne(int sid)throws Exception {
File file=new File(filePath);
if(!file.exists()) {
return null;
}
BufferedReader bin=new BufferedReader(new FileReader(file));
Student student=null;
String line;
while((line=bin.readLine())!=null) {
line=line.trim();
if(line.isEmpty()) {
continue;
}
if(line.startsWith(sid+":")) {
student=parseString(line);
break;
}
}
bin.close();
return student;
}
public static List<Student> getAll()throws Exception {
File file=new File(filePath);
if(!file.exists()) {
return null;
}
BufferedReader bin=new BufferedReader(new FileReader(file));
List<Student> list=new ArrayList<Student>();
String line;
while((line=bin.readLine())!=null) {
line=line.trim();
if(line.isEmpty()) {
continue;
}
list.add(parseString(line));
}
bin.close();
return list;
}
public static int deleteOne(int sid)throws Exception {
List<Student> list=getAll();
for (int i = 0; i <list.size(); i++) {
if(list.get(i).getSid().equals(sid)) {
list.remove(i);
break;
}
}
StringBuffer stb=new StringBuffer();
for (Student s : list) {
stb.append(s);
stb.append("\r\n");
}
writeString(stb.toString(),false);
return 1;
}
public static int updateOne(Student s)throws Exception {
List<Student> list=getAll();
for (int i = 0; i <list.size(); i++) {
if(list.get(i).getSid().equals(s.getSid())) {
System.out.println("修改:::");
list.set(i, s);
break;
}
}
StringBuffer stb=new StringBuffer();
for (Student stu : list) {
stb.append(stu);
stb.append("\r\n");
}
writeString(stb.toString(),false);
return 1;
}
private static void writeString(String str,boolean append)throws Exception {
FileWriter fout=new FileWriter(filePath, append);
fout.write(str);
fout.close();
}
private static Student parseString(String line) {
String[] arr=line.split(":");
return new Student(Integer.parseInt(arr[0]),
arr[1],
arr[2],
Float.parseFloat(arr[3]),
Integer.parseInt(arr[4]),
Boolean.parseBoolean(arr[5]));
}
}
class Student{
private Integer sid;
private String sname;
private String sex;
private Float score;
private Integer sage;
private Boolean sdy;
@Override
public String toString() {
return sid + ":" + sname + ":" + sex + ":" + score + ":" + sage+ ":" + sdy ;
}
public Integer getSid() {
return sid;
}
public void setSid(Integer sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Float getScore() {
return score;
}
public void setScore(Float score) {
this.score = score;
}
public Integer getSage() {
return sage;
}
public void setSage(Integer sage) {
this.sage = sage;
}
public Boolean getSdy() {
return sdy;
}
public void setSdy(Boolean sdy) {
this.sdy = sdy;
}
public Student(Integer sid, String sname, String sex, Float score, Integer sage, Boolean sdy) {
super();
this.sid = sid;
this.sname = sname;
this.sex = sex;
this.score = score;
this.sage = sage;
this.sdy = sdy;
}
public Student(String sname, String sex, Float score, Integer sage, Boolean sdy) {
super();
this.sname = sname;
this.sex = sex;
this.score = score;
this.sage = sage;
this.sdy = sdy;
}
public Student() {}
}
5.3 练习3
public static void test01()throws Exception{
BufferedReader bin=new BufferedReader(new FileReader("src/Test/Demo02.txt"));
FileWriter outsz=new FileWriter("src/Test/Demo02_数字.txt");
FileWriter outzm=new FileWriter("src/Test/Demo02_字母.txt");
FileWriter outqt=new FileWriter("src/Test/Demo02_其他.txt");
String line;
while((line=bin.readLine())!=null) {
for (int i = 0; i < line.length(); i++) {
char c=line.charAt(i);
if(Character.isDigit(c)) {
outsz.write(c);
outsz.flush();
}else if(Character.isLowerCase(c)||Character.isUpperCase(c)) {
outzm.write(c);
outzm.flush();
}else {
outqt.write(c);
outqt.flush();
}
}
}
bin.close();
outqt.close();
outzm.close();
outsz.close();
}
5.4 练习4
public static void test02()throws Exception {
File yuan=new File("src/Test/Demo02.txt");
File muDi=new File("src/Test/Demo02_1.txt");
BufferedReader bin=new BufferedReader(new FileReader(yuan));
BufferedWriter bout=new BufferedWriter(new FileWriter(muDi));
String line;
while((line=bin.readLine())!=null) {
line=changeStr2(line);
bout.write(line);
bout.flush();
bout.newLine();
bout.flush();
}
bin.close();
bout.close();
yuan.delete();
muDi.renameTo(yuan);
}
private static String changeStr2(String str) {
StringBuffer stb=new StringBuffer(str);
for (int i = 0; i < stb.length(); i++) {
char c=stb.charAt(i);
if(Character.isLowerCase(c)) {
stb.setCharAt(i,Character.toUpperCase(c));
}else if(Character.isUpperCase(c)) {
stb.setCharAt(i, Character.toLowerCase(c));
}else if(Character.isDigit(c)) {
stb.deleteCharAt(i);
i--;
}
}
return stb.toString();
}
6 PrintWriter
* PrintWriter:打印输出流
* 特点1:没有对应的输入流
* 特点2:可以作为节点流(关联的是文件) 还可以作为过滤流(关联其他流)
*
* 构造方法:
* PrintWriter(File file)
* PrintWriter(String fileName)
* PrintWriter(OutputStream out)
* PrintWriter(OutputStream out, boolean autoFlush)
* PrintWriter(Writer out)
* PrintWriter(Writer out, boolean autoFlush)
* 注意:如果autoFlush为true::println、printf方法 会自动刷新
*
*普通方法:
* void close()
* void flush()
* void write(int c)
* void write(String s)
* void write(char[] buf)
*特有方法:
* void print(Object obj) :::保持数据的原有状态
* void println(Object obj)
7 序列化
package day14_io;
import java.io.Serializable;
import java.util.UUID;
public class Teacher implements Serializable {
private Integer tid;
private String tname;
private float tsalary;
private char tsex;
public Integer getTid() {
return tid;
}
public void setTid(Integer tid) {
this.tid = tid;
}
public String getTname() {
return tname;
}
public void setTname(String tname) {
this.tname = tname;
}
public float getTsalary() {
return tsalary;
}
public void setTsalary(float tsalary) {
this.tsalary = tsalary;
}
public char getTsex() {
return tsex;
}
public void setTsex(char tsex) {
this.tsex = tsex;
}
@Override
public String toString() {
return "Teacher [tid=" + tid + ", tname=" + tname + ", tsalary=" + tsalary + ", tsex=" + tsex + "]";
}
public Teacher(Integer tid, String tname, float tsalary, char tsex) {
super();
this.tid = tid;
this.tname = tname;
this.tsalary = tsalary;
this.tsex = tsex;
}
public Teacher() {
this.tname=UUID.randomUUID().toString().replace("-", "").substring(5, 11);
this.tid=(int)(Math.random()*1000+1000);
this.tsalary=(int)(Math.random()*30000+10000)/10.0f;
this.tsex=Math.random()>0.5?'男':'女';
}
}
package day14_io;
....
public class Demo06ObjectStream {
public static void main(String[] args)throws Exception{
List<Teacher> list=new ArrayList<Teacher>();
list=testObjectInputStream();
for (Teacher teacher : list) {
System.out.println(teacher);
}
}
public static void testObjectOutputStream(List<Teacher> list)throws Exception{
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream("src/day14_io/teacher.mm"));
for (Teacher teacher : list) {
oos.writeObject(teacher);
System.out.println(teacher);
}
oos.close();
}
public static List<Teacher> testObjectInputStream()throws Exception{
ObjectInputStream ois=new ObjectInputStream(new FileInputStream("src/day14_io/teacher.mm"));
List<Teacher> list=new ArrayList<>();
for (;true;) {
try {
Teacher t=(Teacher)ois.readObject();
list.add(t);
}catch(EOFException e) {
break;
}
}
ois.close();
return list;
}
}