java IO流学习
javaIO流学习笔记
BuffedReader
import com.lfm.BufferedReader_;
import java.io.BufferedReader;
import java.io.FileReader;
public class BufferdReader_ {
public static void main(String[] args) throws Exception{
String path = "/home/lfm/java_study/Test/src/Solution.java";
//创建
BufferedReader br = new BufferedReader(new FileReader(path));
//读取
String line;//按行读取
while((line = br.readLine()) != null) {
System.out.println(line);
}
//这里只需要关闭BufferedReader,因为底层会自动去关节点流
br.close();
/*
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();//in 就是我们传入的new FileReader(path)
} finally {
in = null;
cb = null;
}
}
}
*/
}
}
- 关闭(close) 的源码
public void close() throws IOException {
synchronized (lock) {
if (in == null)
return;
try {
in.close();//in 就是我们传入的new FileReader(path)
} finally {
in = null;
cb = null;
}
}
}
BufferedWriter
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class BufferedWriter_ {
public static void main(String[] args) throws IOException {
String filePath = "/home/lfm/test_io/ok.txt";
//创建一个
BufferedWriter bw = new BufferedWriter(new FileWriter(filePath, true));
bw.write("hello , lfm");
bw.newLine();
bw.write("hello2 , lfm");
bw.newLine();
bw.write("hello3 , lfm");
bw.newLine();
//插入一个换行符
//FileWriter会自动关闭
bw.close();
}
}
复制文件
import java.io.*;
public class BufferedCopy_ {
public static void main(String[] args) {
String srcFilepath = "/home/lfm/java_study/Test/src/Main.java";
String destFilepath = "/home/lfm/test_io/note.txt";
//1. BufferedWriter BufferedReader 是字符操作,不要操作二进制文件
BufferedReader br = null;
BufferedWriter bw = null;
String line = null;
try {
br = new BufferedReader(new FileReader(srcFilepath));
bw = new BufferedWriter(new FileWriter(destFilepath));
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
} catch (IOException e) {
try {
throw new IOException(e);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
} finally {
//关闭
try {
if (br != null)
br.close();
if (bw != null)
bw.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
拷贝二进制文件
import com.lfm.BufferedReader_;
import java.io.*;
/**
* 演示使用BufferedOutputStream 和 BufferedInputStream使用
* 使用他们可以完成二进制文件拷贝
* 思考:字节流可以操作二进制文件,可以操作文本文件吗?
*/
public class BufferedCopy02 {
public static void main(String[] args) {
String srcFilePath = "/home/lfm/test_io/note.txt";
String destFilePath = "/home/lfm/test_io/ok.txt";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
//循环读取文件
byte[] buff = new byte[1024];
int readLine = 0;
while ((readLine = bis.read(buff)) != -1) {
}
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//关闭外层处理流
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
节点流和处理流
/home/lfm/.jdks/corretto-1.8.0_462/bin/java -javaagent:/home/lfm/.local/share/JetBrains/Toolbox/apps/intellij-idea-ultimate/lib/idea_rt.jar=43533 -Dfile.encoding=UTF-8 -classpath /home/lfm/.jdks/corretto-1.8.0_462/jre/lib/charsets.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/cldrdata.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/dnsns.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/jaccess.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/jfxrt.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/localedata.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/nashorn.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/sunec.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/sunjce_provider.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/sunpkcs11.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/ext/zipfs.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/jce.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/jfr.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/jfxswt.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/jsse.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/management-agent.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/resources.jar:/home/lfm/.jdks/corretto-1.8.0_462/jre/lib/rt.jar:/home/lfm/java_study/chapter19/out/production/chapter19:/home/lfm/.m2/repository/org/junit/jupiter/junit-jupiter/5.8.1/junit-jupiter-5.8.1.jar:/home/lfm/.m2/repository/org/junit/jupiter/junit-jupiter-api/5.8.1/junit-jupiter-api-5.8.1.jar:/home/lfm/.m2/repository/org/opentest4j/opentest4j/1.2.0/opentest4j-1.2.0.jar:/home/lfm/.m2/repository/org/junit/platform/junit-platform-commons/1.8.1/junit-platform-commons-1.8.1.jar:/home/lfm/.m2/repository/org/apiguardian/apiguardian-api/1.1.2/apiguardian-api-1.1.2.jar:/home/lfm/.m2/repository/org/junit/jupiter/junit-jupiter-params/5.8.1/junit-jupiter-params-5.8.1.jar:/home/lfm/.m2/repository/org/junit/jupiter/junit-jupiter-engine/5.8.1/junit-jupiter-engine-5.8.1.jar:/home/lfm/.m2/repository/org/junit/platform/junit-platform-engine/1.8.1/junit-platform-engine-1.8.1.jar com.lfm.outputstream_.ObjecttOutStream_
Exception in thread "main" java.io.NotSerializableException: com.lfm.outputstream_.Dog
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1184)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:348)
at com.lfm.outputstream_.ObjecttOutStream_.main(ObjecttOutStream_.java:22)
进程已结束,退出代码为 1
报错是因为没有实现序列化接口,Dog类没有实现Serializable接口,所以无法序列化。
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class ObjecttOutStream_ {
public static void main(String[] args) throws IOException {
//序列化后保存的文件格式不是纯文本的,而是按照
String filePath = "/home/lfm/test_io/data.dat";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到 /home/lfm/test_io/data.dat
oos.write(100);// ->Integer
oos.writeBoolean(true);//->Boolean
oos.writeChar('a');//-> Character
oos.writeDouble(3.14);//double -> Double
oos.writeUTF("lfm");//String
//保存一个dog对象
oos.writeObject(new Dog("旺财", 10));
oos.close();
System.out.println("数据保存完成");
}
}
class Dog {
private String name;
private int age;
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
}
节点流和处理流
介绍:
-
InputstreamReader:Reader的子类, 可以将InputStream(字节流) 包装(转换) Reader(字符流)
-
OutputStreamWriter:Writer的子类, 可以将OutputStream(字节流) 包装(转换) Writer(字符流)
-
当处理纯文本数据时, 如果使用字符流效率更高,并且可以有效解决中文问题,所以建议将字节流转换成字符流
-
可以在使用时指定编码格式比如UTF-8,GBK等, 否则默认使用平台默认编码格式
public class InputStreamReader_ {
public static void main(String[] args) throws Exception {
String filePath = "/home/lfm/test_io/note.txt";
//1. new FileInputStream 转成InputStreamReader
//2. 指定编码utf8
//InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "utf8");
////3. 把InputStreamReader 传入 BufferedReader
//BufferedReader br = new BufferedReader(isr);
//合在一起
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "utf8"));
//4. 读取
String s = br.readLine();
System.out.println("读取内容 = " + s);
//5.关闭外层
br.close();
}
}
- note.txt内容是gbk编码的要想在我的arch系统打印出来,没有乱码
引入InputStreamReader 包装InputStream, 然后指定编码格式为utf8, 这样就可以正确打印出中文了。
输出流
PrintStream
import java.io.IOException;
import java.io.PrintStream;
import java.io.PrintWriter;
/**
* 演示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("你好");
//因为print底层使用的是write,所以我们可以直接调用write进行打印/输出
out.write("lfm".getBytes());
out.close();
//1. 输出修改到 "/home/lfm/test_io/note.txt"
//2. "hello,lfm" 就会输出到"/home/lfm/test_io/note.txt"
//3.
//public static void setOut(PrintStream out) {
// checkIO();
// setOut0(out);//native 方法 修改了out
//}
System.setOut(new PrintStream("/home/lfm/test_io/note.txt"));
System.out.println("hello,lfm");
}
}
PrintWriter
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
public class PrintWriter_ {
public static void main(String[] args) throws IOException {
//PrintWriter out = new PrintWriter(System.out);
PrintWriter out = new PrintWriter(new FileWriter("/home/lfm/test_io/note.txt"));
out.println("你好李富民");
out.flush();
out.close();
}
}
- 注意
要关闭流或者刷新流才能写进去
Properties
- 专门用于读写配置文件的集合类
配置文件的格式:
键=值
键值对之间用=号分隔,每行一个键值对
- 看一个需求
如下一个配置文件
id = 192.168.0.13
user = root
password = 123456
读取配置文件
import java.io.FileReader;
import java.util.Properties;
public class Properties02 {
public static void main(String[] args) throws Exception {
//使用Properties 类来读取mysql.properties文件
//1. 创建Properties 对象
Properties properties = new Properties();
properties.load(new FileReader("src/mysql.properties"));
//2. 加载指定配置文件
properties.load(new FileReader("src/mysql.properties"));
//3. 把k-v显示控制台
properties.list(System.out);
//4. 根据key 获取对应的值
String user = properties.getProperty("user");
System.out.println(user);
String password = properties.getProperty("password");
System.out.println(password);
}
}
对配置文件进行修改
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;
public class Properties03 {
public static void main(String[] args) throws IOException {
//使用Properties类来创建配置文件, 修改配置内容
Properties properties = new Properties();
//创建
//如果没用键就是创建
//有的话就是修改
/*
Properties 的父类就是HashTable
public synchronized Object setProperty(String key, String value) {
return put(key, value);
}
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (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<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}
addEntry(hash, key, value, index);
return null;
}
*/
properties.setProperty("charset", "utf8");
properties.setProperty("user", "汤姆");
properties.setProperty("pwd", "888888888");
//将k-v存储到文件中
properties.store(new FileOutputStream("src/mysql2.properties"), "hello world");
System.out.println("保存配置文件成功");
}
}

浙公网安备 33010602011771号