1.File
1.1File类概述
Java File类是用于管理文件和目录的类,它提供了一系列方法来操作文件系统中的文件和目录。File类可以用于创建、删除、重命名、复制、移动文件或目录等操作。可以通过File类实例化一个文件对象,然后使用这个对象调用相应的方法来完成文件和目录的操作。
1.2File类常用API
1.创建一个File对象
File(String pathname):根据指定的路径名称创建File对象。
2.exists()
判断文件是否存在并且删除,如果存在并且删除返回true,否则返回false。
String s ="D:/Test";
File f =new File(s);
System.out.println(f.exists());

3.isFile()
判断是否为文件或者目录是否存在
String s ="D:/qipan.jpeg";
File f =new File(s);
System.out.println(f.isFile());


4.isDirectory()
判断是否为目录,是否是一个文件夹是返回true,否返回false
String s ="D:/qipan.jpeg";
File f =new File(s);
System.out.println(f.isDirectory());

5.getName()
获取文件名字
String s ="D:/qipan.jpeg";
File f =new File(s);
System.out.println(f.getName());

6.getAbsolutePath()
获取文件绝对路径
String s ="D:/qipan.jpeg";
File f =new File(s);
System.out.println(f.getAbsoluteFile());

2.InputStream
2.1概述
InputStream是抽象类,无法实例化,需要实现子类。InputStream/OutPutStream为字节流基类(超类或父类),字节流的类通常以stream结尾。它们的子类都是字节流,主要用在按字节来处理二进制数据。字节流是最基本的,采用ASCII编码
2.2InputStream常用子类
1.FileInputStream:文件字节输入流
FileInputStream 是 Java 语言中抽象类 InputStream 用来具体实现类的创建对象。
public static void main(String[] args) throws IOException {
FileInputStream f=null;//创建一个对象
try {
f =new FileInputStream(new File("D:/snuts.html"));//InputStream里面需要放一个File对象,我们在里面直接创了一个新的
} catch (FileNotFoundException e) {
e.getMessage();
}
int read=f.read();//当f.read为负一时表示读取完成
while (read!=-1){
System.out.print((char) read);//因为是int型所以要类型转换
read=f.read();
}
}


我们可以让他一次读取多个字节加快速度
public static void main(String[] args) throws IOException {
FileInputStream f=null;//创建一个对象
byte[] b =new byte[100];//
try {
f =new FileInputStream(new File("D:/snuts.html"));//InputStream里面需要放一个File对象,我们在里面直接创了一个新的
} catch (FileNotFoundException e) {
e.getMessage();
}
int read=f.read(b);//当f.read为负一时表示读取完成
while (f.read(b)!=-1){
System.out.print(new String(b,0,read));//因为是int型所以要类型转换
read=f.read(b);
}
f.close();
}
这样比之前要快很多,操作完之后,需要关闭这个流,否则造成资源浪费,引用close方法即可
3.OutputStream
3.1概述
FileOutputStream流是指文件字节输出流,专用于输出原始字节流如图像数据等,其继承OutputStream类,拥有输出流的基本特性,OutputStream 抽象类,所有输出字节字节流的父类FileOutputStream 向文件输出数据的输出字节流。
FileOutputStream f =null;
f=new FileOutputStream("D:/1.txt");
try {
f.write('a');
}catch (NumberFormatException e){
e.printStackTrace();
e.getMessage();
System.out.println("写入失败");
}
f.close();

FileOutputStream f =null;
f=new FileOutputStream("D:/1.txt");
try {
String s ="你好世界";
f.write(s.getBytes());
}catch (NumberFormatException e){
e.printStackTrace();
e.getMessage();
System.out.println("写入失败");
}
f.close();

&spm=1001.2101.3001.5002&articleId=140043124&d=1&t=3&u=09d52ee542124be0954e8cbd42f16ca7)
2万+

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



