文件就是保存数据的地方
文件在程序中以
流
的形式进行操作
- 流:数据在数据源(文件)和 程序(内存)之间经历的路径
- 输出流:java 程序(内存) ————> 文件(磁盘)
- 输入流: java 程序 (内存) <———— 文件(磁盘)
new File(String pathname)
new File(File parent,String child)
new File(String parent,String child)
创建文件的方法 createNewFile()
具体方法如下
// 1. new File(String pathname)方式
public void create01() {String filename = "e:\\news1.txt";File file = new File(filename);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();System.out.println("文件创建失败");}}// 2. new File(File parent,String child)public void create02() {File parent = new File("e:\\");String childName = "news2.txt";File file = new File(parent, childName);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();System.out.println("文件创建失败");}}// 3. new File(String parent,String child)public void create03() {String parent = "e:\\";String child = "news3.txt";File file = new File(parent, child);try {file.createNewFile();System.out.println("文件创建成功");} catch (IOException e) {e.printStackTrace();System.out.println("文件创建失败");}}
UTF-8编码
一个英文字母一字节 一个汉字三字节 以hello世界为例:11字节// 获取文件信息public void getInfo() {// 先创建文件对象File file = new File("e://news1.txt");if (file.exists()) {System.out.println("文件名:" + file.getName());System.out.println("文件路径:" + file.getPath());System.out.println("文件父目录: " + file.getParent());System.out.println("文件大小(单位字节):" + file.length());} else {System.out.println("该文件不存在");}}
delete()
返回值为boolean
类型mkdir
一级目录 mkdirs
多级目录 // 如果文件存在 则删除文件public void m1() {String filePath = "e:\\news1.txt";File file = new File(filePath);if (file.exists()) {System.out.println(filePath + " 文件存在");boolean flag = file.delete();if (flag) {System.out.println(filePath + " 文件被删除!!!");} else {System.out.println(filePath + " 文件删除失败~~~");}} else {System.out.println(filePath + " 文件不存在...");}}
// mkdir创建一级目录 mkdirs 创建多级目录public void m2() {String directoryName = "e:\\demo";File file = new File(directoryName);if (file.exists()) {System.out.println(directoryName + " 目录已经存在");} else {boolean flag = file.mkdir();if (flag) {System.out.println(directoryName + " 目录创建成功");} else {System.out.println(directoryName + " 目录创建失败");}}}
- i/o 技术 input output 用于处理数据的传输 如:读写文件,网络通讯
- java程序中对数据的输入与输出以
流stream
的方式进行- java.io包下提供各种流和数据
抽象基类 | 字节流 | 字符流 |
---|---|---|
输入流 | InputStream | Reader |
输出流 | OutputStream | Writer |
FileInputStream.read()
单个字节读取,效率比较低 返回值为int 需要强转为char
/*** 演示读取文件*/@Testpublic void readFile01() {String filePath = "e:\\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();}}}
FileInputStream.read(byte[])
/*** 使用read(byte[] b) 读取文件 提高效率*/@Testpublic void readFile02() {String filePath = "e:\\hello.txt";// 定义字节数组byte[] buf = new byte[8]; // 一次读取8个字节int readLength = 0;FileInputStream fileInputStream = null;try {// 创建FileInputStream 用于读取文件fileInputStream = new FileInputStream(filePath);// 按传入的字节数组进行读取//fileInputStream().read(buf)返回实际读取的字节数while ((readLength = fileInputStream.read(buf)) != -1) {System.out.print((new String(buf,0,readLength))); //转成char形式}} catch (IOException e) {e.printStackTrace();} finally {// 关闭流,释放资源try {fileInputStream.close();} catch (IOException e) {e.printStackTrace();}}}
注:new FileOutputStream(filePath) 是覆盖方式 new FileOutputStream(filePath,true) 是追加方式
package com.ttc.file;import org.junit.Test;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() {String filePath = "e:\\a.txt";// 创建 FileOutputStream对象FileOutputStream fileOutputStream = null;try {// new.FileOutputStream(filePath) 创建方式:覆盖方式 写入内容时会覆盖原来的内容// new FileOutPutStream(filePath,true) 则是追加方式 在文件末尾写入// 得到FileOutputStream流 对象// fileOutputStream = new FileOutputStream(filePath);fileOutputStream = new FileOutputStream(filePath, true);// 方法1. 写入一个字节// fileOutputStream.write('T');//方法2. 写入字符串String str = "hello world";// str.getBytes() 可以以 把字符串 转换为字节数组// fileOutputStream.write(str.getBytes());// 方法3. FileOutputStream.write(byte[],off,length)fileOutputStream.write(str.getBytes(), 0, str.length());} catch (IOException e) {System.out.println("写入失败!");e.printStackTrace();} finally {try {System.out.println("写入成功~");fileOutputStream.close();System.out.println("关闭流");} catch (IOException e) {e.printStackTrace();System.out.println("流关闭失败");}}}
}
输入流与输出流结合
package com.ttc.file;import org.junit.Test;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class FileOutputStream01 {public static void main(String[] args) {}/*** 演示用FileOutputStream 将数据写入文件* 如果该文件不存在 将会自动创建文件*/@Testpublic void writeFile() {String filePath = "e:\\a.txt";// 创建 FileOutputStream对象FileOutputStream fileOutputStream = null;try {// new.FileOutputStream(filePath) 创建方式:覆盖方式 写入内容时会覆盖原来的内容// new FileOutPutStream(filePath,true) 则是追加方式 在文件末尾写入// 得到FileOutputStream流 对象// fileOutputStream = new FileOutputStream(filePath);fileOutputStream = new FileOutputStream(filePath, true);// 方法1. 写入一个字节// fileOutputStream.write('T');//方法2. 写入字符串String str = "hello world";// str.getBytes() 可以以 把字符串 转换为字节数组// fileOutputStream.write(str.getBytes());// 方法3. FileOutputStream.write(byte[],off,length)fileOutputStream.write(str.getBytes(), 0, str.length());} catch (IOException e) {System.out.println("写入失败!");e.printStackTrace();} finally {try {System.out.println("写入成功~");fileOutputStream.close();System.out.println("关闭输出流");FileInputStream fileInputStream = new FileInputStream(filePath);byte[] buf = new byte[8];int fileLength = 0;while ((fileLength = fileInputStream.read(buf)) != -1) {System.out.print(new String(buf, 0, fileLength));}fileInputStream.close();System.out.println("\n关闭输入流!");} catch (IOException e) {e.printStackTrace();System.out.println("流关闭失败");}}}
}
完成
文件的拷贝
将e:\test.png 拷贝 到 d:\
- 创建文件输入流,将文件写入到程序
- 创建文件输出流,将读取到的文件数据,写入到指定的位置
注: 完成程序时,应该读取部分数据就写入到指定位置中,使用循环
package com.ttc.file;import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;/*** 完成文件的拷贝*/
public class FileCopy01 {public static void main(String[] args) {
/* 1. 创建文件输入流,将文件写入到程序2. 创建文件输出流,将读取到的文件数据,写入到指定的位置注: 完成程序时,应该读取部分数据就写入到指定位置中,使用循环*/String srcFilePath = "e:\\test.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 实现 边读边写fileOutputStream.write(buf, 0, readLen);}System.out.println("拷贝ok~");} catch (IOException e) {e.printStackTrace();} finally {try {// 关闭输入流和输出流,释放资源if (fileInputStream != null) {fileInputStream.close();}if (fileOutputStream != null) {fileOutputStream.close();}} catch (IOException e) {e.printStackTrace();}}}
}
FileReader
FileWriter
tocharArray
将string 转换为char[]使用FileReader
读取文件
package com.ttc.file;import org.junit.Test;import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;public class FileReader_ {public static void main(String[] args) {// 1. 创建一个FileReader对象String filePath = "e:\\a.txt";FileReader fileReader = null;int data = 0;try {fileReader = new FileReader(filePath);// 循环读取 方法 1.使用read.读取单个字符while ((data = fileReader.read()) != -1) {System.out.print((char) data);}} catch (IOException e) {e.printStackTrace();} finally {try {if (fileReader != null) {fileReader.close();System.out.println("流关闭成功");}} catch (IOException e) {e.printStackTrace();}}}/*** 方法2.使用char[] 加快文件读取效率*/@Testpublic void readFile02() {String filePath = "e:\\a.txt";FileReader fileReader = null;char[] buf = new char[1024];int readLen = 0;try {fileReader = new FileReader(filePath);// 使用read(buf)返回的是实际读取的字符数 -1 表示结束while ((readLen = fileReader.read(buf)) != -1) {System.out.println(new String(buf, 0, readLen));}} catch (IOException e) {e.printStackTrace();} finally {try {fileReader.close();System.out.println("流关闭成功");} catch (IOException e) {e.printStackTrace();}}}
}
FileWriter
写文件package com.ttc.file;import java.io.FileWriter;
import java.io.IOException;public class FileWriter_ {public static void main(String[] args) {String filePath = "e:\\note.txt";char[] chars = {'a', 'b', 'c', 'd'};// 创建FileWriterFileWriter fileWriter = null;try {fileWriter = new FileWriter(filePath); // 默认覆盖方式写入// 1.write(char) 写入单个字符fileWriter.write('H');// 2.write(char[]) 写入字符数组fileWriter.write(chars);// 3.write(char[],off,len) 写入字符数组,截取指定长度// 用String.toCharArray 可以将String转化为char[]fileWriter.write("你好哇世界".toCharArray(), 0, 3);// 4.write(string) 写入字符串fileWriter.write(" java从入门到精通");// 5.write(string,off,len) 指定字符的长度和位置fileWriter.write("我是兔兔小淘气,面对世界很好奇!!!", 0, 10);} catch (IOException e) {e.printStackTrace();} finally {// FileWriter 一定要close或者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();}*/if (fileWriter != null) {try {
// fileWriter.flush(); // 刷新// close 等价于 flush + 关闭fileWriter.close();System.out.println("输出流关闭");} catch (IOException e) {e.printStackTrace();}}}System.out.println("程序结束!!!");}
}
上一篇: 学生心理辅导活动方案
下一篇: 竞争上岗方案