
Java知识点--IO流(上)
一、文件
1、文件的含义
文件是保存数据的地方,比如word文档,txt文本文件,视频,图片等都是文件。
2、文件流
文件在程序中是以流的形式来操作的。
输入流:数据从文件到程序(内存)的路径。(在程序中读取文件数据)
输出流:数据从程序(内存)到文件的路径。(在程序中将数据写入文件)
二、常用的文件操作
1、创建文件对象相关构造器和方法
相关构造器:
new File(String filePath) 根据路径创建File对象
new File(File parent,String child) 根据父目录文件+子路径创建File对象
new File(tring parent,String child) 根据父目录+子路径创建File对象
方法:
createNewFile 创建新文件
2、创建文件案例演示(三种创建方法)
import org.junit.jupiter.api.Test;
import java.io.File;
import java.io.IOException;
public class FileCreate {
public static void main(String[] args) {
}
@Test
public void create01() {
String filePath = "e:\\news1.txt";
File file = new File(filePath);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void create02() {
File parentFile = new File("e:\\");
String fileName = "news2.txt";
File file = new File(parentFile, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void create03() {
String parentPath = "e:\\";
String fileName = "news3.txt";
File file = new File(parentPath, fileName);
try {
file.createNewFile();
System.out.println("文件创建成功");
} catch (IOException e) {
e.printStackTrace();
}
}
}
3、获取文件相关信息的方法
“文件名字” — getName()
“文件绝对路径” — getAbsolutePath()
“文件父级目录” — getParent()
“文件大小(字节)” — length()
“文件是否存在” — exists()
“是不是一个文件” — isFile()
“是不是一个目录” — isDirectory()
4、获取文件相关信息方法案例演示
import org.junit.jupiter.api.Test;
import java.io.File;
public class FileInformation {
public static void main(String[] args) {
}
@Test
public void info(){
File file = new File("e:\\news1.txt");
System.out.println("文件名字" + file.getName());
System.out.println("文件绝对路径" + file.getAbsolutePath());
System.out.println("文件父级目录" + file.getParent());
System.out.
Java.IO流详解:从文件操作到字节流与字符流

这篇博客详细介绍了Java中关于文件和IO流的知识,从文件的基本操作如创建、删除,到IO流的原理和分类。文章重点讲解了字节输入流FileInputStream和字节输出流FileOutputStream的使用,包括如何读取和写入数据,以及如何用字节流拷贝文件。此外,还讨论了字符输入流FileReader和字符输出流FileWriter,提供读取和写入文件的实例。
最低0.47元/天 解锁文章
3635

被折叠的 条评论
为什么被折叠?



