文件,对我们并不陌生,文件是保存数据的地方,比如大家经常使用的word文档,txt文件,excel文件...都是文件。它既可以保存一张图片,也可以保持视频,声音.…
文件在程序中是以流的形式来操作的
请在C盘下,创建文件news1.txt、news2.txt、news3.txt ,用三种不同方式创建。
import org.junit.jupiter.api.Test;import java.io.*;public class FileCreate {public static void main(String[] args) {}//方式1 new File(String pathname)@Testpublic void create01() {String filePath = "C:\\Users\\asus\\Desktop\\java1\\news1.txt";File file = new File(filePath);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();}}//方式2 new File(File parent,String child) //根据父目录文件+子路径构建//e:\\news2.txt@Testpublic void create02() {File parentFile = new File("C:\\Users\\asus\\Desktop\\java1\\");String fileName = "news2.txt";//这里的file对象,在java程序中,只是一个对象//只有执行了createNewFile 方法,才会真正的,在磁盘创建该文件File file = new File(parentFile, fileName);try {file.createNewFile();System.out.println("创建成功~");} catch (IOException e) {e.printStackTrace();}}//方式3 new File(String parent,String child) //根据父目录+子路径构建@Testpublic void create03() {//String parentPath = "e:\\";String parentPath = "C:\\Users\\asus\\Desktop\\java1\\";String fileName = "news4.txt";File file = new File(parentPath, fileName);try {file.createNewFile();System.out.println("创建成功~");} catch (IOException e) {e.printStackTrace();}}//下面四个都是抽象类////InputStream//OutputStream//Reader //字符输入流//Writer //字符输出流
}
getName
getAbsolutePath、
getParent、
length、
exists、
isFile、
isDirectory
import org.junit.jupiter.api.Test;import java.io.File;public class FileInformation {public static void main(String[] args) {}//获取文件的信息@Testpublic void info() {//先创建文件对象File file = new File("C:\\Users\\asus\\Desktop\\java1\\news1.txt");//调用相应的方法,才能得到对应信息System.out.println("文件名字=" + file.getName());//getName、getAbsolutePath、getParent、length、exists、isFile、isDirectorySystem.out.println("文件绝对路径=" + file.getAbsolutePath());System.out.println("文件父级目录=" + file.getParent());System.out.println("文件大小(字节)=" + file.length());System.out.println("文件是否存在=" + file.exists());//TSystem.out.println("是不是一个文件=" + file.isFile());//TSystem.out.println("是不是一个目录=" + file.isDirectory());//F}
}
import org.junit.jupiter.api.Test;import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;public class Directory_ {public static void main(String[] args) {//}//判断 C:\Users\asus\Desktop\java1\\news1.txt 是否存在,如果存在就删除@Testpublic void m1() {String filePath = "C:\\Users\\asus\\Desktop\\java1\\news1.txt";File file = new File(filePath);if (file.exists()) {if (file.delete()) {System.out.println(filePath + "删除成功");} else {System.out.println(filePath + "删除失败");}} else {System.out.println("该文件不存在...");}}//判断 D:\\demo02 是否存在,存在就删除,否则提示不存在//这里我们需要体会到,在java编程中,目录也被当做文件@Testpublic void m2() {String filePath = "D:\\demo02";File file = new File(filePath);if (file.exists()) {if (file.delete()) {System.out.println(filePath + "删除成功");} else {System.out.println(filePath + "删除失败");}} else {System.out.println("该目录不存在...");}}//判断 D:\\demo\\a\\b\\c 目录是否存在,如果存在就提示已经存在,否则就创建@Testpublic void m3() {String directoryPath = "C:\\Users\\asus\\Desktop\\java1\\demo\\a\\b\\c";File file = new File(directoryPath);if (file.exists()) {System.out.println(directoryPath + "存在..");} else {if (file.mkdirs()) { //创建一级目录使用mkdir() ,创建多级目录使用mkdirs()System.out.println(directoryPath + "创建成功..");} else {System.out.println(directoryPath + "创建失败...");}}}
}
2)由这四个类派生出来的子类名称都是以其父类名作为子类名后缀。
要求: 请使用 FileInputStream 读取 hello.txt 文件,并将文件内容显示到控制台。
import org.junit.jupiter.api.Test;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;/*** 演示FileInputStream的使用(字节输入流 文件--> 程序)*/
public class FileInputStream_ {public static void main(String[] args) {}/*** 演示读取文件...* 单个字节的读取,效率比较低* -> 使用 read(byte[] b)*/@Testpublic void readFile01() {String filePath = "C:\\Users\\asus\\Desktop\\java1\\hello.txt";int readData = 0;FileInputStream fileInputStream = null;try {//编译异常//创建 FileInputStream 对象,用于读取 文件fileInputStream = new FileInputStream(filePath);//从该输入流读取一个字节的数据。 如果没有输入可用,此方法将阻止。//如果返回-1 , 表示读取完毕while ((readData = fileInputStream.read()) != -1) {System.out.print((char) readData);//转成char显示}} catch (IOException e) {e.printStackTrace();} finally {//关闭文件流,释放资源.try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}/*** 使用 read(byte[] b) 读取文件,提高效率*/@Testpublic void readFile02() {String filePath = "C:\\Users\\asus\\Desktop\\java1\\hello.txt";//字节数组byte[] buf = new byte[8]; //一次读取8个字节.int readLen = 0;FileInputStream fileInputStream = null;try {//创建 FileInputStream 对象,用于读取 文件fileInputStream = new FileInputStream(filePath);//从该输入流读取最多b.length字节的数据到字节数组。 此方法将阻塞,直到某些输入可用。//如果返回-1 , 表示读取完毕//如果读取正常, 返回实际读取的字节数while ((readLen = fileInputStream.read(buf)) != -1) {System.out.print(new String(buf, 0, readLen));//显示}} catch (IOException e) {e.printStackTrace();} finally {//关闭文件流,释放资源.try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
}
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class FileOutputStream01 {public static void main(String[] args) {}/*** 演示使用FileOutputStream 将数据写到文件中,* 如果该文件不存在,则创建该文件*/@Testpublic void writeFile() {//创建 FileOutputStream对象String filePath = "e:\\a.txt";FileOutputStream fileOutputStream = null;try {//得到 FileOutputStream对象 对象//老师说明//1. new FileOutputStream(filePath) 创建方式,当写入内容是,会覆盖原来的内容//2. new FileOutputStream(filePath, true) 创建方式,当写入内容是,是追加到文件后面fileOutputStream = new FileOutputStream(filePath, true);//写入一个字节//fileOutputStream.write('H');////写入字符串String str = "hsp,world!";//str.getBytes() 可以把 字符串-> 字节数组//fileOutputStream.write(str.getBytes());/*write(byte[] b, int off, int len) 将 len字节从位于偏移量 off的指定字节数组写入此文件输出流*/fileOutputStream.write(str.getBytes(), 0, 3);} catch (IOException e) {e.printStackTrace();} finally {try {fileOutputStream.close();} catch (IOException e) {e.printStackTrace();}}}
}
在完成程序时,应该是读取部分数据,就写入到指定文件,这里使用循环操作。
package com.yt.outputstream_;import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class FileCopy {public static void main(String[] args) {//完成文件拷贝,将C:\\Users\\asus\\Desktop\\java1\\person.png拷贝到C:\\//思路分析//1.创建的文件的输入流,将文件读入到程序//2.创建文件的输出流,将文件写入到指定的位置String srcFilePath = "C:\\Users\\asus\\Desktop\\java1\\person.png";String destFilePath = "C:\\Users\\asus\\Desktop\\java1\\person1.png";FileInputStream fileInputStream = null;FileOutputStream fileOutputStream = null;try {fileInputStream = new FileInputStream(srcFilePath);fileOutputStream = new FileOutputStream(destFilePath);//定义一个字节数组,提高读取效率byte[] buff = new byte[1024];int readLen = 0;while ((readLen=fileInputStream.read(buff)) != -1){//读取到后就写入到文件 通过 fileOutputStream//是边读边写fileOutputStream.write(buff,0,readLen);//一定要使用该方法}System.out.println("拷贝成功");} catch (IOException e) {e.printStackTrace();} finally {try {//关闭输入流和输出流,释放资源if (fileInputStream != null){fileInputStream.close();}if (fileOutputStream != null){fileOutputStream.close();}} catch (IOException e){e.printStackTrace();}}}
}
package com.yt.reader_;import org.junit.jupiter.api.Test;import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class FileReader_ {public static void main(String[] args) {}/*单个字符读取文件*/@Testpublic void readFile01(){String filePath = "C:\\Users\\asus\\Desktop\\java1\\story.txt";FileReader fileReader = null;try {//1.创建一个FileReader对象fileReader = new FileReader(filePath);//循环读取,使用read方法,单个字符读取int data = 0;while ((data=fileReader.read()) != -1){System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null){fileReader.close();}} catch (IOException e) {e.printStackTrace();}}}/*** 使用字符数组读取文件*/@Testpublic void readFile02(){String filePath = "C:\\Users\\asus\\Desktop\\java1\\story.txt";FileReader fileReader = null;try {//1.创建一个FileReader对象fileReader = new FileReader(filePath);//循环读取,使用read(buff)方法,多个字符读取,返回实际读取到的字符数//如果返回-1,说明文件读取完毕char[] buff = new char[1024];int readLen = 0;while ((readLen=fileReader.read(buff)) != -1){System.out.print(new String(buff,0,readLen));}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null){fileReader.close();}} catch (IOException e) {e.printStackTrace();}}}
}
package com.yt.writer_;import java.io.FileWriter;
import java.io.IOException;public class FileWriter_ {public static void main(String[] args) {String filePath = "C:\\Users\\asus\\Desktop\\java1\\note.txt";//创建FileWriter对象FileWriter fileWriter = null;char[] chars = {'a', 'b', 'c'};try {fileWriter = new FileWriter(filePath);//1.write(int):写入单个字符fileWriter.write('H');//2.write(char []):写入指定数组fileWriter.write(chars);//3.write(char[],off,len):写入指定数组的指定部分fileWriter.write("你好呀哈哈哈".toCharArray(), 0, 3);//4.write(String):写入整个字符串fileWriter.write("你好北京——");//5.write(String,off,len):写入字符串的指定部分fileWriter.write("上海天津", 0, 2);//在数据量大的情况下,使用循环写入System.out.println("程序结束");} catch (IOException e) {e.printStackTrace();} finally {//对于FileWriter,一定要关闭流或者flush才能真正的写入到文件/*看看源码private void writeBytes() throws IOException {this.bb.flip();int var1 = this.bb.limit();int var2 = this.bb.position();assert var2 <= var1;int var3 = var2 <= var1 ? var1 - var2 : 0;if (var3 > 0) {if (this.ch != null) {assert this.ch.write(this.bb) == var3 : var3;} else {this.out.write(this.bb.array(), this.bb.arrayOffset() + var2, var3);}}this.bb.clear();}*/try {
// fileWriter.close();fileWriter.flush();} catch (IOException e) {e.printStackTrace();}}}
}
处理流的功能主要体现在以下两个方面:
1.使用BufferedReader读取文本文件,并显示在控制台。
源码
package com.yt.reader_;import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;/*** 演示BufferedReader的使用*/
public class BufferedReader_ {public static void main(String[] args) throws Exception {String filePath = "C:\\Users\\asus\\Desktop\\java1\\a.java";//创建BufferedReader的对象BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));//读取String line;//按行读取,效率高//1.bufferedReader.readLine()是按行读取文件,//2.当返回一个null时,表示文件读取完毕while ((line = bufferedReader.readLine()) != null) {System.out.println(line);}//关闭流//只需要关闭外层流,bufferedReader即可,因为底层会自动的关闭节点流/*源码public void close() throws IOException {synchronized (lock) {if (in == null)return;try {in.close();} finally {in = null;cb = null;}}}*/bufferedReader.close();}
}
2.使用BufferedWriter将”hello,北京”,写入到文件中。
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;/*** 演示BufferedWriter的使用*/
public class BufferedWriter_ {public static void main(String[] args) throws IOException {String filePath = "e:\\ok.txt";//创建BufferedWriter//说明://1. new FileWriter(filePath, true) 表示以追加的方式写入//2. new FileWriter(filePath) , 表示以覆盖的方式写入BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath));bufferedWriter.write("hello, 韩顺平教育!");bufferedWriter.newLine();//插入一个和系统相关的换行bufferedWriter.write("hello2, 韩顺平教育!");bufferedWriter.newLine();bufferedWriter.write("hello3, 韩顺平教育!");bufferedWriter.newLine();//说明:关闭外层流即可 , 传入的 new FileWriter(filePath) ,会在底层关闭bufferedWriter.close();}
}
3)综合使用BufferedReader和 BufferedWriter完成文本文件拷贝,注意文件编码
package com.yt.writer_;import java.io.*;public class BufferedCopy {public static void main(String[] args) {//特别强调//1.BufferedReader和BufferedWriter是按照字符操作的//2.不要去操作二进制文件(声音,视频,Word),可能造成文件的损坏String srcFilePath = "C:\\Users\\asus\\Desktop\\java1\\a.java";String destFilePath = "C:\\Users\\asus\\Desktop\\java1\\a2.java";BufferedReader bufferedReader = null;BufferedWriter bufferedWriter = null;String line;try {bufferedReader = new BufferedReader(new FileReader(srcFilePath));bufferedWriter = new BufferedWriter(new FileWriter(destFilePath));//读取//说明readline()方法没有换行符while ((line = bufferedReader.readLine()) != null){//每读取一行就写入bufferedWriter.write(line);//务必记得换行bufferedWriter.newLine();}System.out.println("拷贝完毕");} catch (IOException e) {e.printStackTrace();} finally {//关闭流try {if (bufferedReader != null) {bufferedReader.close();}if (bufferedWriter != null){bufferedWriter.close();}} catch (IOException e) {e.printStackTrace();}}}
}
要求:编程完成图片/音乐的拷贝(要求使用Buffered..流).
package com.yt.outputstream_;import java.io.*;/*** 演示使用BufferedOutputStream和BufferedInputStream,可以完成二进制文件的拷贝*/
public class BufferedCopy02 {public static void main(String[] args) {String srcFilePath = "C:\\Users\\asus\\Desktop\\java1\\person.png";String destFilePath = "C:\\Users\\asus\\Desktop\\java1\\person03.png";BufferedInputStream bufferedInputStream = null;BufferedOutputStream bufferedOutputStream = null;try {//创建对象//FileInputStream 是 InputStream 的子类bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFilePath));bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(destFilePath));byte[] buff = new byte[1024];int readLen = 0;//循环的读取文件,并写完文件//当返回-1时表示文件读取完毕while ((readLen = bufferedInputStream.read(buff))!= -1) {bufferedOutputStream.write(buff,0,readLen);}System.out.println("文件拷贝完毕");} catch (IOException e) {e.printStackTrace();} finally {//关闭流//关闭外层流即可(处理流),底层会去关闭节点流try {if (bufferedInputStream != null){bufferedInputStream.close();}if (bufferedOutputStream != null){bufferedOutputStream.close();}} catch (IOException e) {e.printStackTrace();}}}
}
看一个需求
1.将int num = 100这个int数据保存到文件中,注意不是100数字,而是int 100,并且,能够从文件中直接恢复int 100
2.将Dog dog = new Dog(“小黄”,3)这个 dog对象保存到文件中,并且能够从文件恢复.
3.上面的要求,就是能够将基本数据类型或者对象进行序列化和反序列化操作.
序列化和反序列化:
- 序列化就是在保存数据时,保存数据的值和数据类型
- 反序列化就是在恢复数据时,恢复数据的值和数据类型
- 需要让某个对象支持序列化机制,则必须让其类是可序列化的,为了让某个类是可序列化的,该类必须实现如下两个接口之一:
- Serializable //这是一个标记接口,是没有方法的
- Externalizable//该接口有方法需要实现,
- 因此我们一般实现上面的Serializable接口
功能:提供了对基本类型或对象类型的序列化和反序列化的方法
ObjectOutputStream 提供 序列化功能
ObjectInputStream 提供 反序列化功能
1.使用ObjectOutputStream序列化基本数据类型和一个 Dog对象(name, age).并保存到data.txt 文件中.
package com.yt.outputstream_;import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;/*** 演示ObjectOutputStream的使用,完成数据的序列化*/
public class ObjectOutputStream_ {public static void main(String[] args) throws Exception{//序列化后,保存的文件格式不是纯文本的,而是按照格式来进行保存的String filePath = "C:\\Users\\asus\\Desktop\\java1\\serializable\\data.txt";ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));//序列化数据到指定位置objectOutputStream.write(100);//int-->Integer(实现了Serializable接口)objectOutputStream.writeBoolean(true);//boolean --> BooleanobjectOutputStream.writeChar('a');//char --> CharacterobjectOutputStream.writeDouble(9.7);//double --> DoubleobjectOutputStream.writeUTF("你好啊");//String也实现了Serializable接口objectOutputStream.writeObject(new Dog("旺财",10));objectOutputStream.close();System.out.println("数据保存完毕(序列化形式)");}
}
//如果需要序列化某个类的对象,必须实现Serializable接口
class Dog implements Serializable {private String name;private int age;public Dog(String name, int age) {this.name = name;this.age = age;}
}
2.使用ObjectlnputStream读取data.txt 并反序列化恢复数据
package com.yt.inputstream_;import com.yt.outputstream_.Dog;import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.Serializable;public class ObjectInputStream_ {public static void main(String[] args) throws IOException, ClassNotFoundException {//指定反序列化的文件String filePath = "C:\\Users\\asus\\Desktop\\java1\\serializable\\data.txt";ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath));//读取//注意:读取(反序列化)的顺序需要和保存数据(序列化)的顺序一致//否则会出现异常System.out.println(objectInputStream.readInt());System.out.println(objectInputStream.readBoolean());System.out.println(objectInputStream.readChar());System.out.println(objectInputStream.readDouble());System.out.println(objectInputStream.readUTF());//dog的编译类型是Object,运行类型是DogObject dog = objectInputStream.readObject();System.out.println("运行类型是:" + dog.getClass());//运行类型是DogSystem.out.println("dog信息=" + dog);//底层会将Object --> Dog//特别重要的细节://如果我们希望调用Dog的方法//就需要向下转型,所有要将Dog类的定义拷贝到可以引用的位置Dog dog1 = (Dog)dog;System.out.println(dog1.getName());//关闭流objectInputStream.close();}
}
注意事项和细节说明:
1)读写顺序要一致。
2)要求序列化或反序列化对象,需要实现Serializable。
3)序列化的类中建议添加SerialVersionUID,为了提高版本的兼容性。
4)序列化对象时,默认将里面所有属性都进行序列化,但除了static或transient修饰的成员。
5)序列化对象时,要求里面属性的类型也需要实现序列化接口。
6)序列化具备可继承性,也就是如果某类已经实现了序列化,则它的所有子类也已经默认实现了序列化。
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Scanner;public class InputAndOutput {public static void main(String[] args) {//System 类 的 public final static InputStream in = null;// System.in 编译类型 InputStream// System.in 运行类型 BufferedInputStream// 表示的是标准输入 键盘System.out.println(System.in.getClass());//老韩解读//1. System.out public final static PrintStream out = null;//2. 编译类型 PrintStream//3. 运行类型 PrintStream//4. 表示标准输出 显示器System.out.println(System.out.getClass());System.out.println("hello, 韩顺平教育~");Scanner scanner = new Scanner(System.in);System.out.println("输入内容");String next = scanner.next();System.out.println("next=" + next);}
}
先看一个文件乱码问题,引出学习转换流必要性。
package com.yt.transformation;import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;/*** 看一个中文乱码问题*/
public class CodeQuestion {public static void main(String[] args) throws IOException {//读取指定位置的文件到程序String filePath = "C:\\Users\\asus\\Desktop\\java1\\a.txt";//1.创建字符输入流BufferedReader(处理流)//2.使用BufferedReader对象读取文件//3.默认情况下,读取文件是按照utf-8编码的BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));String str = bufferedReader.readLine();System.out.println(str);bufferedReader.close();}
}
1.编程将字节流FilelnputStream 包装成(转换成)字符流InputStreamReader,对
文件进行读取(按照utf-8/gbk格式),进而在包装成 BufferedReader。
import java.io.*;/*** 演示使用 InputStreamReader 转换流解决中文乱码问题* 将字节流 FileInputStream 转成字符流 InputStreamReader, 指定编码 gbk/utf-8*/
public class InputStreamReader_ {public static void main(String[] args) throws IOException {String filePath = "C:\\Users\\asus\\Desktop\\java1\\a.txt";//解读//1. 把 FileInputStream 转成 InputStreamReader//2. 指定编码 gbk//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");//3. 把 InputStreamReader 传入 BufferedReader//BufferedReader br = new BufferedReader(isr);//将2 和 3 合在一起BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "gbk"));//4. 读取String s = br.readLine();System.out.println("读取内容=" + s);//5. 关闭外层流br.close();}}
2编程将字节流 FileOutputStream 包装成(转换成)字符流OutputStreamWriter,对文件进行写入(按照gbk格式,可以指定其他,比如utf-8)
import java.io.*;/*** 演示 OutputStreamWriter 使用* 把FileOutputStream 字节流,转成字符流 OutputStreamWriter* 指定处理的编码 gbk/utf-8/utf8*/
public class OutputStreamWriter_ {public static void main(String[] args) throws IOException {String filePath = "C:\\Users\\asus\\Desktop\\java1\\a.txt";String charSet = "utf-8";OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);osw.write("hi, 韩顺平教育");osw.close();System.out.println("按照 " + charSet + " 保存文件成功~");}
}
打印流只有输出流,没有输入流
import java.io.IOException;
import java.io.PrintStream;/*** 演示PrintStream (字节打印流/输出流)*/
public class PrintStream_ {public static void main(String[] args) throws IOException {PrintStream out = System.out;//在默认情况下,PrintStream 输出数据的位置是 标准输出,即显示器/*public void print(String s) {if (s == null) {s = "null";}write(s);}*/out.print("john, hello");//因为print底层使用的是write , 所以我们可以直接调用write进行打印/输出out.write("韩顺平,你好".getBytes());out.close();//我们可以去修改打印流输出的位置/设备//1. 输出修改成到 "e:\\f1.txt"//2. "hello, 韩顺平教育~" 就会输出到 e:\f1.txt//3. public static void setOut(PrintStream out) {// checkIO();// setOut0(out); // native 方法,修改了out// }System.setOut(new PrintStream("e:\\f1.txt"));System.out.println("hello, 韩顺平教育~");}
}
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;/*** 演示 PrintWriter 使用方式*/
public class PrintWriter_ {public static void main(String[] args) throws IOException {//PrintWriter printWriter = new PrintWriter(System.out);PrintWriter printWriter = new PrintWriter(new FileWriter("e:\\f2.txt"));printWriter.print("hi, 北京你好~~~~");printWriter.close();//flush + 关闭流, 才会将数据写入到文件..}
}
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class Properties01 {public static void main(String[] args) throws IOException {//读取mysql.properties 文件,并得到ip, user 和 pwdBufferedReader br = new BufferedReader(new FileReader("src\\mysql.properties"));String line = "";while ((line = br.readLine()) != null) { //循环读取String[] split = line.split("=");//如果我们要求指定的ip值if("ip".equals(split[0])) {System.out.println(split[0] + "值是: " + split[1]);}}br.close();}
}
1)专门用于读写配置文件的集合类
配置文件的格式:
键=值
键=值
2)注意:键值对不需要有空格,值不需要用引号一起来。默认类型是String
load:加载配置文件的键值对到Properties对象
list:将数据显示到指定设备
getProperty(key):根据键获取值
setProperty(key,value):设置键值对到Properties对象
store:将Properties中的键值对存储到配置文件,在idea中,保存信息到配置文件,如果含有中文,会存储为unicode码
unicode码查询工具:http://tool.chinaz.com/tools/unicode.aspx
1.使用Properties类完成对mysql.properties的读取
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;public class Properties02 {public static void main(String[] args) throws IOException {//使用Properties 类来读取mysql.properties 文件//1. 创建Properties 对象Properties properties = new Properties();//2. 加载指定配置文件properties.load(new FileReader("src\\mysql.properties"));//3. 把k-v显示控制台properties.list(System.out);//4. 根据key 获取对应的值String user = properties.getProperty("user");String pwd = properties.getProperty("pwd");System.out.println("用户名=" + user);System.out.println("密码是=" + pwd);}
}
2.使用Properties类添加key-val到新文件mysql2.properties中
3.使用Properties类完成对 mysq12.properties的读取,并修改某个key-val
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;public class Properties03 {public static void main(String[] args) throws IOException {//使用Properties 类来创建 配置文件, 修改配置文件内容Properties properties = new Properties();//创建//1.如果该文件没有key 就是创建//2.如果该文件有key ,就是修改/*Properties 父类是 Hashtable , 底层就是Hashtable 核心方法public synchronized V put(K key, V value) {// Make sure the value is not nullif (value == null) {throw new NullPointerException();}// Makes sure the key is not already in the hashtable.Entry,?> tab[] = table;int hash = key.hashCode();int index = (hash & 0x7FFFFFFF) % tab.length;@SuppressWarnings("unchecked")Entry entry = (Entry)tab[index];for(; entry != null ; entry = entry.next) {if ((entry.hash == hash) && entry.key.equals(key)) {V old = entry.value;entry.value = value;//如果key 存在,就替换return old;}}addEntry(hash, key, value, index);//如果是新k, 就addEntryreturn null;}*/properties.setProperty("charset", "utf8");properties.setProperty("user", "汤姆");//注意保存时,是中文的 unicode码值properties.setProperty("pwd", "888888");//将k-v 存储文件中即可properties.store(new FileOutputStream("src\\mysql2.properties"), null);System.out.println("保存配置文件成功~");}
}
(1)在判断e盘下是否有文件夹mytemp ,如果没有就创建mytemp
(2)在e:\mytemp目录下,创建文件hello.txt
(3)如果hello.txt已经存在,提示该文件已经存在,就不要再重复创建了
(4)并且在hello.txt文件中,写入hello,world~
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;public class Homework01 {public static void main(String[] args) throws IOException {/***(1) 在判断e盘下是否有文件夹mytemp ,如果没有就创建mytemp*(2) 在e:\\mytemp 目录下, 创建文件 hello.txt*(3) 如果hello.txt 已经存在,提示该文件已经存在,就不要再重复创建了*(4) 并且在hello.txt 文件中,写入 hello,world~*/String directoryPath = "e:\\mytemp";File file = new File(directoryPath);if(!file.exists()) {//创建if(file.mkdirs()) {System.out.println("创建 " + directoryPath + " 创建成功" );}else {System.out.println("创建 " + directoryPath + " 创建失败");}}String filePath = directoryPath + "\\hello.txt";// e:\mytemp\hello.txtfile = new File(filePath);if(!file.exists()) {//创建文件if(file.createNewFile()) {System.out.println(filePath + " 创建成功~");//如果文件存在,我们就使用BufferedWriter 字符输入流写入内容BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));bufferedWriter.write("hello, world");bufferedWriter.close();} else {System.out.println(filePath + " 创建失败~");}} else {//如果文件已经存在,给出提示信息System.out.println(filePath + " 已经存在,不在重复创建...");}}
}
要求:使用BufferedReader读取一个文本文件,为每行加上行号,再连同内容一并输出到屏幕上。
如果老韩把文件的编码改成了gbk,出现中文乱码,大家思考如何解决
1.默认是按照utf-8处理,开始没有乱码
2.提示:使用我们的转换流,将FilelnputStream -> InputStreamReader[可以指定编码->BufferedReader ...
package com.yt.homework;import java.io.*;public class Homework02 {public static void main(String[] args) {String filePath = "C:\\Users\\asus\\Desktop\\java1\\a.txt";BufferedReader bufferedReader = null;String line = "";//用于保存读出的字符串int lineNum = 0;//保存行数try {//使用转换流InputStreamReader(new FileInputStream(filePath),"gbk"))构造器来指定编码InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(filePath),"gbk");bufferedReader= new BufferedReader(inputStreamReader);while ((line=bufferedReader.readLine()) != null){System.out.println((++lineNum) + " " + line);}} catch (IOException e) {e.printStackTrace();} finally {try {if (bufferedReader != null) {bufferedReader.close();}} catch (IOException e) {e.printStackTrace();}}}
}
(1)要编写一个dog.properties
name=tom
age=5
color=red
(2)编写Dog 类(name,age,color)创建一个dog对象,读取dog.properties用相应的内容完成属性初始化.并输出
(3)将创建的Dog对象,序列化到文件dog.dat文件
package com.yt.homework;import org.junit.jupiter.api.Test;import java.io.*;
import java.util.Properties;public class Homework03 {public static void main(String[] args) throws IOException {Properties properties = new Properties();//编写文件里面的信息properties.setProperty("name","tom");properties.setProperty("age","5");properties.setProperty("color","red");//保存文件信息properties.store(new FileWriter("src\\com\\yt\\dog.properties"),null);//加载配置文件properties.load(new FileReader("src\\com\\yt\\dog.properties"));//获得Dog类对应的属性String name = properties.getProperty("name") + "";//Object-->Stringint age = Integer.parseInt(properties.getProperty("age") + "");//Object-->intString color = properties.getProperty("color") + "";//Object-->StringDog dog = new Dog(name, age, color);System.out.println("dog对象的信息:");System.out.println(dog);//创建的dog对象,将其序列化存到dog.txt文件中String filePath = "C:\\Users\\asus\\Desktop\\java1\\dog.txt";ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(filePath));objectOutputStream.writeObject(dog);//关闭流objectOutputStream.close();}//实现dog的反序列化@Testpublic void m1() throws IOException, ClassNotFoundException {String filePath = "C:\\Users\\asus\\Desktop\\java1\\dog.txt";ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(filePath));Dog dog = (Dog)objectInputStream.readObject();System.out.println("反序列化后");System.out.println(dog);objectInputStream.close();}
}
class Dog implements Serializable{private String name;private int age;private String color;public Dog(String name, int age, String color) {this.name = name;this.age = age;this.color = color;}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}@Overridepublic String toString() {return "Dog{" +"name='" + name + '\'' +", age=" + age +", color='" + color + '\'' +'}';}
}