标签:String System IO import new public out
IO
创建文件
package com.IO;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
//创建文件
public class FileCreate {
public static void main(String[] args) {
}
//方式1、new File(String pathname)
@Test
public void create01() {
String filepath = "D:\\JAVA_IO_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)
@Test
public void create02() {
File parentFile = new File("D:\\");
String filename = "JAVA_IO_news2.txt";
//这里的file对象只是java程序中的一个对象,并不是具体到磁盘上的文件
File file = new File(parentFile, filename);
try {
file.createNewFile();//该操作将生成具体的磁盘上的文件
System.out.println("第二种文件创建方式创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
//方式3、根据父目录 + 子路径构建:new File(String parent,String child)
@Test
public void create03() {
String parentPath = "D:\\";
String filePath = "JAVA_IO_news3.txt";
File file = new File(parentPath, filePath);
try {
file.createNewFile();
System.out.println("第三种文件创建方式创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
获取文件信息
package com.IO;
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
public class FileInformation {
public static void main(String[] args) {
}
//获取文件信息
@Test
public void info() throws IOException {
//先创建文件对象
File file = new File("D:\\news1.txt");
file.createNewFile();
//调用相应的方法,得到对应信息
//getName,getAbsolutePath,getParent,length,exists,isFile,isDirectory
System.out.println("文件名字 = " + file.getName());
System.out.println("文件绝对路径:"+file.getAbsoluteFile());
System.out.println("getParent:"+file.getParent());
System.out.println("length:"+file.length());//计算字节大小
System.out.println("exists:"+file.exists());
System.out.println("isFile:"+file.isFile());
System.out.println("isDirectory:"+file.isDirectory());
}
}
目录操作
package com.IO;
import org.junit.jupiter.api.Test;
import java.io.File;
public class Directory_ {
public static void main(String[] args) {
}
//判断文件是否存在,存在则删除
@Test
public void m1() {
String filePath = "D:\\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(filePath + "文件不存在");
}
}
//判断目录是否存在,存在则删除
@Test
public void m2() {
String directoryPath = "D:\\demo02";
File file = new File(directoryPath);
if (file.exists()) {
if (file.delete()) {
System.out.println(directoryPath + "文件删除成功");
} else {
System.out.println(directoryPath + "文件删除失败");
}
} else {
System.out.println(directoryPath + "文件不存在");
}
}
//判断目录是否存在,不存在则创建
@Test
public void m3() {
String directoryPath = "D:\\demo03";
File file = new File(directoryPath);
if (file.exists()) {
System.out.println(directoryPath + "目录已存在");
} else {
if (file.mkdir()) {//多级目录要使用 mkdirs
System.out.println(directoryPath + "目录创建成功");
} else {
System.out.println(directoryPath + "目录创建失败");
}
}
}
}
InputStream
package com.IO.inputstream;
import org.junit.jupiter.api.Test;
import java.io.FileInputStream;
import java.io.IOException;
public class FileInputStream_ {
public static void main(String[] args) {
}
//读取文件(字节流)read()方法
@Test
public void readFile01() {
String filePath = "D:\\news01.txt";
int readData = 0;
FileInputStream fileInputStream = null;
try {
//FileInputStream用于读取文件
fileInputStream = new FileInputStream(filePath);
//fileInputStream.read():从该输入流读取一个字节的数据。如果没有输入可用,该方法将阻止
//返回-1,表示读取完毕
while ((readData = fileInputStream.read()) != -1) {
System.out.print((char) readData);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭输入流
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//读取文件(字节流)read(byte[] b)方法
@Test
public void readFile02() {
String filePath = "D:\\news01.txt";
FileInputStream fileInputStream = null;
int readLen = 0;
//定义一个字节数组
byte[] bytes = new byte[8];//一次读取8个字节
try {
//FileInputStream用于读取文件
fileInputStream = new FileInputStream(filePath);
//fileInputStream.read(byte[] b):从该输入流最多读取b.length长度的数据到字节数组
//fileInputStream.read(byte[] b):返回实际读取的字节数
//返回-1,表示读取完毕
while ((readLen = (fileInputStream.read(bytes))) != -1) {
System.out.print(new String(bytes, 0, readLen));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
//关闭输入流
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
OutputStream
package com.IO.OutputStream;
import org.junit.jupiter.api.Test;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileOutputStream_ {
public static void main(String[] args) {
}
//数据写入到文件
@Test
public void writeFile() {
//创建 FileOutputStream对象
String filePath = "D:\\news02.txt";
FileOutputStream fileOutputStream = null;
try {
//1、当使用new FileOutputStream(filePath)构造方式时,写入内容会覆盖原来的内容
//2、使用new FileOutputStream(filePath,true)构造方式时,写入内容会追加到原来的内容后
fileOutputStream = new FileOutputStream(filePath,true);
//写入一个字节
//fileOutputStream.write('H');
//写入字符串
//getBytes():将 字符串 转成 字节数组
String str = "hello,world";
fileOutputStream.write(str.getBytes());
//write(byte b[], int off, int len)方法:只写入指定位置的数组
fileOutputStream.write(str.getBytes(),0,str.length());
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件拷贝操作
package com.IO;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class FileCopy {
public static void main(String[] args) {
//文件拷贝
//先用输入流将文件写入,再用输出流将文件写出,完成文件的拷贝
//news03.txt->news04.txt
String srcFilePath = "D:\\微信截图.png";
String DestFilePath = "D:\\test.png";
FileInputStream fileInputStream = null;
FileOutputStream fileOutputStream = null;
try {
fileInputStream = new FileInputStream(srcFilePath);
fileOutputStream = new FileOutputStream(DestFilePath);
//用数组来读取
byte[] buf = new byte[1024];
int readLen = 0;
while ((readLen = fileInputStream.read(buf)) != -1) {
//读取到源文件后,就写入到目标文件,边读边写
fileOutputStream.write(buf, 0, buf.length);
}
System.out.println("文件拷贝成功");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
fileOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
文件字符流
FileReader
package com.IO.reader;
import org.junit.jupiter.api.Test;
import java.io.FileReader;
import java.io.IOException;
public class FileReader_ {
public static void main(String[] args) {
String filePath = "D:\\news03.txt";
FileReader fileReader = null;
int data = 0;
//1、创建FileReader对象
try {
fileReader = new FileReader(filePath);
//循环读取 使用read,单个字符读取
while ((data = fileReader.read()) != -1) {
System.out.print((char) data);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//第二种方法
@Test
public void ReadFile02() {
String filePath = "D:\\news03.txt";
FileReader fileReader = null;
int readLen = 0;
char[] buf = new char[8];
//1、创建FileReader对象
try {
fileReader = new FileReader(filePath);
//循环读取 使用read(buf)返回读取到的字符数
while ((readLen = fileReader.read(buf)) != -1) {
System.out.print(new String(buf, 0, readLen));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
FileWriter
package com.IO.Writer;
import java.io.FileWriter;
import java.io.IOException;
public class FileWriter_ {
public static void main(String[] args) {
String filePath = "D:\\news04.txt";
FileWriter fileWriter = null;
char[] chars = {'a', 'b', 'c', 'd'};
try {
fileWriter = new FileWriter(filePath, true);
//1、write()方法:写入单个字符
//fileWriter.write('H');
//2、write(char[])方法:写入指定数组
//fileWriter.write(chars);
//3、write(char[],off,len)方法:写入指定数组的指定部分
//fileWriter.write("北京欢迎你".toCharArray(), 0, 5);
//4、write(String)方法:写入整个字符串
//fileWriter.write("你好,深圳!");
//5、write(String,off,len)方法:写入字符串的指定部分
fileWriter.write("最美重庆,天下", 0, 4);
//在数据量大的情况下,可以使用循环操作
} catch (IOException e) {
e.printStackTrace();
} finally {
//对应fileWriter,一定要关闭流或者flush操作才能真正把数据写入到文件中去
try {
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
节点流和处理流
- 节点流:可以从一个特定的数据源读写数据,如FileReader,FileWriter,是底层流/低级流,直接和数据源相接
- 处理流:是连接在已经存在的流之上,位程序提供更为强大的读写功能,如BufferedReader,BufferedWriter
- 包装节点流,既可以消除不同节点流的实现差异,也可以提供更方便的方法完成输入输出
- 对节点流进行包装,使用了修饰器设计模式,不会直接与数据源相连
- 关闭的时候只需要关闭外层即可
模拟修饰器设计模式
package com.IO.decoratorDesignPatternTest;
public abstract class Reader_ {//抽象类
public void readFile_() {
}
public void readString_() {
}
}
package com.IO.decoratorDesignPatternTest;
public class FileReader_ extends Reader_ {
public void readFile_() {
System.out.println("对文件进行读取...");
}
}
package com.IO.decoratorDesignPatternTest;
public class StringReader_ extends Reader_ {
public void readString_(){
System.out.println("读取字符串...");
}
}
package com.IO.decoratorDesignPatternTest;
//处理流模拟
public class BufferedReader_ extends Reader_ {
private Reader_ reader_;
//接收Reader_子类对象
public BufferedReader_(Reader_ reader_) {
this.reader_ = reader_;
}
//多次读取文件
public void readFiles(int num) {
for (int i = 0; i < num; i++) {
reader_.readFile_();
}
}
public void readFile_(){
reader_.readFile_();
}
//扩展readString,批量处理字符串数据
public void readStrings(int num) {
for (int i = 0; i < num; i++) {
reader_.readString_();
}
}
public void readString_(){
reader_.readString_();
}
}
测试结果:
package com.IO.decoratorDesignPatternTest;
public class Test_ {
public static void main(String[] args) {
BufferedReader_ bufferedReader_ = new BufferedReader_(new FileReader_());
bufferedReader_.readFile_();
BufferedReader_ bufferedReader_1 = new BufferedReader_(new StringReader_());
bufferedReader_1.readStrings(5);
}
}
BufferedReader
package com.IO.reader;
import java.io.BufferedReader;
import java.io.FileReader;
public class BufferedReader_ {
public static void main(String[] args) throws Exception {
String filePath = "D:\\news01.txt";
BufferedReader bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
//readLine()按行读取文件
//返回值为空表示读取完文件
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
//关闭流,只需要关闭外层,就是bufferedReader,底层会自动去关闭FileReader节点流
bufferedReader.close();
}
}
BufferedWriter
package com.IO.writer;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class BufferedWriter_ {
public static void main(String[] args) throws Exception{
String filePath = "D:\\news02.txt";
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(filePath,true));
bufferedWriter.write("BufferedWriter写入测试!!!");
bufferedWriter.write("BufferedWriter写入测试!!!");
bufferedWriter.newLine();//插入一个和系统相关的换行
bufferedWriter.write("BufferedWriter写入测试!!!");
bufferedWriter.write("BufferedWriter写入测试!!!");
bufferedWriter.write("BufferedWriter写入测试!!!");
bufferedWriter.close();
}
}
Buffered拷贝
package com.IO;
import java.io.*;
public class BufferedCopy_ {
public static void main(String[] args) {
//BufferedReader、BufferedWriter是按照字符操作的,不要去操作二进制文件,可能会造成文件损坏(声音、视频、PDF,WORD文档)
String srcFilePath = "D:\\news01.txt";
String destFilePath = "D:\\news01_copyHere.txt";
BufferedReader br = null;
BufferedWriter bw = null;
String line;
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) {
e.printStackTrace();
} finally {
//关闭流
try {
if (br != null) {
br.close();
}
if (bw != null) {
bw.close();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
字节流拷贝文件
package com.IO.outputStream;
import java.io.*;
//字节处理流(包装流拷贝文件)
//可以操作二进制文件
public class BufferedCopy02 {
public static void main(String[] args) {
String srcFilePath = "D:\\news01.txt";
String destFilePath = "D:\\mews01_BufferedCopy02_CopyHere.txt";
//创建BufferedInputStream对象、BufferedOutputStream对象
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bis = new BufferedInputStream(new FileInputStream(srcFilePath));
bos = new BufferedOutputStream(new FileOutputStream(destFilePath));
//循环读取文件,并写入到destFilePath
byte[] buff = new byte[1024];
int readLen = 0;
while ((readLen = bis.read(buff)) != -1) {
bos.write(buff, 0, buff.length);
}
System.out.println("文件拷贝成功");
} catch (IOException e) {
e.printStackTrace();
}finally {
//关闭流
if (bis!=null){
try {
bis.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (bos!=null){
try {
bos.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
对象处理流
对象流:ObjectInputStream和ObjectOutputStream
能够将基本数据类型或者对象进行序列化和反序列化的操作
- 序列化:保存数据时,保存数据的值和数据类型
- 反序列化:恢复数据时,恢复数据的值和数据类型
- 要想让某个对象支持序列化机制,则其类必须是可序列化的,那么该类必须实现如下两个接口之一:
- Serializable //标记接口,没有方法
- Externalizable
- 注意事项和细节:
- 序列化和反序列化的读写顺序要一致
- 对象需要实现Serializable
- 序列化的类中建议添加SerializableUID,提高版本的兼容性
- 序列化对象时,默认将里面的所有属性都序列化,但除了static和transient修饰的成员
- 序列化对象时,要求里面的属性也需要实现序列化接口
- 序列化具备可继承性,也就是如果某类已经实现了序列化,则他的所有子类默认实现了序列化
ObjectOutputStream 和 ObjectInputStream
package com.IO.outputStream;
import java.io.Serializable;
//要序列化某个类的对象,这个类就要实现Serializable
public class Dog implements Serializable {
private String name;
private int age;
//SerializableUID 序列化的版本号,可以提高兼容性
public Dog(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Dog{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
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;
}
}
package com.IO.outputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class ObjectOutputStream_ {
public static void main(String[] args) throws Exception {
//序列化后,保存的文件格式,不是文本,而是按照他的格式来保存
String filePath = "D:\\news05.txt";
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
//序列化数据到:D:\news05.txt
oos.writeInt(100);
oos.writeBoolean(true);
oos.writeChar('c');
oos.writeDouble(11.13);
oos.writeUTF("北京欢迎您");
//保存一个对象
oos.writeObject(new Dog("apple", 3));
oos.close();
System.out.println("数据保存完毕");
}
}
package com.IO.inputstream;
import com.IO.outputStream.Dog;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class ObjectInputStream_ {
public static void main(String[] args) throws Exception {
//选中要反序列化的文件
String filePath = "D:\\news05.txt";
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filePath));
//读取文件
//读取(反序列化)要和保存数据(序列化)的顺序一致
System.out.println(ois.readInt());
System.out.println(ois.readBoolean());
System.out.println(ois.readChar());
System.out.println(ois.readDouble());
System.out.println(ois.readUTF());
//dog的编译类型是 Object , dog的运行类型是 Dog
Object dog = ois.readObject();
System.out.println("dog的运行类型:" + dog.getClass());
System.out.println("dog的信息:"+dog);
//如果需要调用Dog类的方法,需要先向下转型
Dog dog2 = (Dog) dog;
System.out.println(dog2.getName());
ois.close();
}
}
标准输入输出流
package com.IO.standard;
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());//class java.io.BufferedInputStream
//System.out public final static PrintStream out = null;
//编译类型 PrintStream
//运行类型 PrintStream
//表示的是标准输出 显示器
System.out.println(System.out.getClass());//class java.io.PrintStream
}
}
转换流
直接读取可能会出现问题的代码:
package com.IO.transformation;
import java.io.BufferedReader;
import java.io.FileReader;
public class CodeQuestion {
public static void main(String[] args) throws Exception {
//读取D:\\news01.txt文件到程序
//创建字符输入流 BufferedReader[]
//使用 BufferedReader 对象读取 news01.txt
//默认情况下,读取文件是按照 UTF-8 编码
String filePath = "D:\\\\news01.txt";
BufferedReader buf = new BufferedReader(new FileReader(filePath));
System.out.println(buf.readLine());
buf.close();
//InputStreamReader
//OutputStreamWriter
}
}
操作文件属性:
输出结果:
可见出现了乱码,使用转换流处理:
InputStreamReader
package com.IO.transformation;
import java.io.*;
//InputStreamReader 转换流解决中文乱码问题
public class InputStreamReader_ {
public static void main(String[] args) throws Exception {
String filePath = "D:\\news01.txt";
//1、new FileInputStream 转成 new InputStreamReader
//2、指定编码 gbk
InputStreamReader isr = new InputStreamReader(new FileInputStream(filePath), "gbk");
//3、把 InputStreamReader 传入 BufferedReader
BufferedReader br = new BufferedReader(isr);
//4、读取
String s = br.readLine();
System.out.println(s);
br.close();
}
}
输出结果:
OutputStreamWriter
package com.IO.transformation;
import java.io.*;
public class OutputStreamWriter_ {
public static void main(String[] args) throws Exception {
String filePath = "D:\\news02.txt";
String charSet = "utf-8";
OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(filePath), charSet);
osw.write("你好,北京");
osw.close();
System.out.println("按照 " + charSet + " 方式保存成功");
}
}
PrintStream
package com.IO.printStream;
import java.io.IOException;
import java.io.PrintStream;
public class PrintStream_ {
public static void main(String[] args) throws IOException {
PrintStream out = System.out;
//在默认情况下,PrintStream 输出数据的位置是标准输出,即显示器
out.print("Hello the world!");
//print 也是使用的 write 方法来输出的,所以我们也可以直接使用 write 方法来输出
out.write("Hello the world!".getBytes());
out.close();
//修改打印流输出的位置/设备
System.setOut(new PrintStream("D:\\news02.txt"));
System.out.println("修改打印流输出---测试");
}
}
PrintWriter
package com.IO.transformation;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class printWriter_ {
public static void main(String[] args) throws IOException {
//PrintWriter printWriter = new PrintWriter(System.out);
PrintWriter printWriter = new PrintWriter(new FileWriter("D:\\news01.txt"));
printWriter.print("你好,北京");
printWriter.close();//flush + 关闭流,才会将数据写入到文件
}
}
Properties
package com.IO.properties;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class Properties_ {
public static void main(String[] args) throws IOException {
//读取 mysql.properties 文件,得到 ip,user,pwd
BufferedReader br = new BufferedReader(new FileReader("D:\\Projects\\JavaSE\\javase\\src\\mysql.properties"));
String line = "";
while ((line = br.readLine()) != null) {
String[] split = line.split("=");
System.out.println(split[0] + " 值是:" + split[1]);
}
}
}
package com.IO.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("D:\\Projects\\JavaSE\\javase\\src\\mysql.properties"));
//3、将 k-v显示到控制台
properties.list(System.out);
//4、根据 key 获取 value
String user = properties.getProperty("user");
String pwd = properties.getProperty("pwd");
System.out.println("用户名:" + user);
System.out.println("密码:" + pwd);
}
}
package com.IO.properties;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Propertied03 {
public static void main(String[] args) throws IOException {
//使用properties 来创建配置文件,修改配置文件内容
Properties properties = new Properties();
//创建
//如果 key 不存在,这是创建;如果已经存在 key 就是修改
properties.setProperty("charset", "utf8");
properties.setProperty("user", "阿拉善");
properties.setProperty("pwd", "654321");
//将 k-v 存储到文件中
properties.store(new FileOutputStream("D:\\Projects\\JavaSE\\javase\\src\\mysql2.properties"), null);
System.out.println("保存配置文件成功~");
}
}
标签:String,System,IO,import,new,public,out 来源: https://www.cnblogs.com/xiaojian1995/p/16548527.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。