Java IO流笔记

默默赞一下老师超好用的PPT

File 类

ps:注意file的delete失败可能是输入输出流还在用这个file

Java实现简单文件管理

 1 package fileDemo;
 2 
 3 import java.io.File;
 4 import java.util.Scanner;
 5 
 6 public class DirExp {
 7 
 8     public static boolean isDirectory(String path) {
 9         File file = new File(path);
10         return file.isDirectory();
11     }
12     
13     public static boolean isExists(String path) {
14         File file = new File(path);
15         return file.exists();
16     }
17     
18     public static String [] getSubFiles(String path) {
19         File file = new File(path);
20         return file.list();
21     }
22     
23     
24     public static void main(String[] args) {
25         Scanner cin = new Scanner(System.in);
26         String path = "";
27         path = cin.nextLine();
28         if(!DirExp.isDirectory(path)) {
29             System.out.println("It's not a directory.");
30             return ;
31         } 
32         if(!DirExp.isExists(path)) {
33             System.out.println("It's not existe.");
34             return ;
35         }
36         String []subFiles = DirExp.getSubFiles(path);
37         for(String s: subFiles) {
38             System.out.println(s);
39         }
40         cin.close();
41     }
42 
43 }

FileInputStream 和 FileOutputStream

 

java实现粘贴文件和剪切文件的功能

 1 package fileDemo;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 
 8 public class FileOperation {
 9 
10     public static int copyFile(String path1, String path2) throws IOException {
11 
12         File file1 = new File(path1);
13         File file2 = new File(path2);
14         if(!file1.isFile()) {
15             return -1;
16         }
17         if(!file1.exists()) {
18             return -2;
19         }
20         
21 
22         FileInputStream inputStream = new FileInputStream(file1);
23         FileOutputStream outputStream = new FileOutputStream(file2);
24  
25         byte data[] = new byte[(int)file1.length()];
26         inputStream.read(data);
27         for(byte a: data) {
28             System.out.print((char)a);
29             outputStream.write((int)a);
30         }
31         System.out.println();
32         outputStream.close();
33         inputStream.close();
34         return 1;
35     }
36     
37     public static int cutFile(String path1, String path2) throws IOException {
38         int ret = copyFile(path1, path2);
39         if(ret < 0) {
40             return -1;
41         }
42         File file = new File(path1);
43         file.delete();
44         return 1;
45     }
46     
47     public static void main(String[] args) throws IOException {
48         //copyFile("D:\tmp\test.txt", "D:\tmp\test3.txt");
49         cutFile("D:\tmp\test2.txt", "D:\tmp\test3.txt");
50     }
51 
52 }

简单来说: File类针对文件,文件流类使用File的对象创建实例。然后调用read或者write,最后关闭。注意关闭流的顺序

原文地址:https://www.cnblogs.com/Q1143316492/p/8917623.html