输入输出流
文件
*什么是文件
文件就是保存数据的地方
*文件流
文件在程序中以流的方式来操作的
(输入和输出像流水一样)
文件(磁盘)————java程序(内存)
*常用的文件操作
相关方法:
**创建文件
new File(String pathname)//根据路径构建一个File对象
new File(File parent,String child) //根据父目录文件+子路径构建
new File(String parent,String child) //根据父目录+子路径构建
createNewFile 创建新文件
注意:File 类实现了两个接口,Serializable和ComParable接口
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 create1(){
String filename="D:\\news1.txt";
File file=new File(filename);
try {
file.createNewFile();
System.out.println("创建了文件1");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
//2.new File(File parent,String child)
public void create2(){
File file1=new File("D:\\");
String filename="news2.txt";
File file=new File(file1,filename);
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Test
//3. new File(String parent,String child)
public void create3(){
String parentPath="D:\\";
String chileName="news3.txt";
File file=new File(parentPath,chileName);
try {
file.createNewFile();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
**获取文件的信息
getName(),获取文件的名字
getAbsolutePath(), 获取文件的绝对路径
getParent(), 获取文件的父级目录
length(), 获取 文件的字节(获取字节,指获取文件的所有字节)
exists(), 判断文件是否存在
isFile(), 判断是不是一个文件
isDirectory(), 判断是不是一个目录 **目录的操作和删除
mkdir(), 创建一级目录
mkdirs(), 创建多级目录
delete(), 删除空目录或文件(只能删除空目录的文件) outputstreamWriter与上述相同
*打印流
PrintStream和PrintWriter
打印流只有输出流,没有输入流
printStream是FileOutputStream的子类,而其是OutputStream的子类。所以printStream是字节流
可看PrintWriter是Writer的子类,所以他是字符流
注意:
1.print函数底层使用的是write,所以我们可以直接调用write进行打印/输出
2.我们可以去修改打印流输出的位置/设备
System.setOut(new PrintStream("D:.1.txt")); native方法,修改了out
System.out.println("hello,韩顺平教育~");
*在使用printWriter的时候一定要关闭或者刷新(也是Writer类型的)否则输入不会写入