java中文件操作

1、创建目录/文件

Java中创建文件、目录非常容易。指定文件/目录路径,然后调用mkdir()和createNewFile()方法。

  1. import java.io.File;  
  2.   
  3. public class Main  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         try {  
  8.             File dir = new File("d:\\OJ2");  
  9.             dir.mkdir();  
  10.             File file = new File(dir, "fil1");  
  11.             file.createNewFile();  
  12.         } catch (Exception e) {  
  13.               
  14.         }  
  15.     }  
  16. }  

2、删除文件

调用File.delete()方法

  1. import java.io.File;  
  2.   
  3. public class Main  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         try {  
  8.             File file = new File("d:/OJ2/fil1");  
  9.             if (file.delete()) {  
  10.                 System.out.println(file.getName() + " deleted!");  
  11.             } else {  
  12.                 System.out.println("file is not deleted.");  
  13.             }  
  14.         } catch (Exception e) {  
  15.               
  16.         }  
  17.     }  
  18. }  

3、一行一行读文件

Java I/O类的数目比较多,很容易混淆什么时候用哪个。下面有两种方式以行方式读文件

方法一:

  1. private static void readFile1(File fin) throws IOException {  
  2.     FileInputStream fis = new FileInputStream(fin);  
  3.    
  4.     //Construct BufferedReader from InputStreamReader  
  5.     BufferedReader br = new BufferedReader(new InputStreamReader(fis));  
  6.    
  7.     String line = null;  
  8.     while ((line = br.readLine()) != null) {  
  9.         System.out.println(line);  
  10.     }  
  11.    
  12.     br.close();  
  13. }  

方法二:

  1. private static void readFile2(File fin) throws IOException {  
  2.     // Construct BufferedReader from FileReader  
  3.     BufferedReader br = new BufferedReader(new FileReader(fin));  
  4.    
  5.     String line = null;  
  6.     while ((line = br.readLine()) != null) {  
  7.         System.out.println(line);  
  8.     }  
  9.    
  10.     br.close();  
  11. }  

这两种方法的区别之处是用什么来构造BufferedReader。方法一是用InputStreamReader,方法二是FileReader.

在Java Doc中,InputStreamReader是连接byte stream和character streams的桥梁,读取字节后,解释成字符。InputStreamReader还能处理除文件外的输入流,如网络连接、类路径资源、zip文件等。

FileReader是方便读取字符的类。该类的构造函数认为默认的字符编码和缓冲大小 是合适的。因此,如果程序运行在不同编码系统中时,不是一种好主意。

总体来说,InputStreamReader相对于FileReader是安全的选择。


4、写文件

下面的代码是写文件的代码,每次执行时,把旧文件删除,再创建新文件。这个不同于追加内容到文件。

  1. public static void writeFile1() throws IOException {  
  2.     File fout = new File("out.txt");  
  3.     FileOutputStream fos = new FileOutputStream(fout);  
  4.    
  5.     BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));  
  6.    
  7.     for (int i = 0; i < 10; i++) {  
  8.         bw.write("something");  
  9.         bw.newLine();  
  10.     }  
  11.    
  12.     bw.close();  
  13. }  

例子中用的是FileOutStream,你也可以用FileWriter或者PrintWriter。

用FileWriter:

  1. public static void writeFile2() throws IOException {  
  2.     FileWriter fw = new FileWriter("out.txt");  
  3.    
  4.     for (int i = 0; i < 10; i++) {  
  5.         fw.write("something");  
  6.     }  
  7.    
  8.     fw.close();  
  9. }  

用PrintWriter:

  1. public static void writeFile3() throws IOException {  
  2.     PrintWriter pw = new PrintWriter(new FileWriter("out.txt"));  
  3.    
  4.     for (int i = 0; i < 10; i++) {  
  5.         pw.write("something");  
  6.     }  
  7.    
  8.     pw.close();  
  9. }  

用OutputStreamWriter:

  1. public static void writeFile4() throws IOException {  
  2.     File fout = new File("out.txt");  
  3.     FileOutputStream fos = new FileOutputStream(fout);  
  4.    
  5.     OutputStreamWriter osw = new OutputStreamWriter(fos);  
  6.    
  7.     for (int i = 0; i < 10; i++) {  
  8.         osw.write("something");  
  9.     }  
  10.    
  11.     osw.close();  
  12. }  

Java Doc:

  1. FileWriter is a convenience class for writing character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are acceptable. To specify these values yourself, construct an OutputStreamWriter on a FileOutputStream.  
  2.   
  3. PrintWriter prints formatted representations of objects to a text-output stream. This class implements all of the print methods found in PrintStream. It does not contain methods for writing raw bytes, for which a program should use unencoded byte streams.  


5、以追加的形式写文件

如果想用代码创建文件,并且删除先前的文件,可以用FileWriter.要替换已存在文件的所有内容,可以用下面的这块代码:

  1. FileWriter fstream = new FileWriter(loc);  

其中loc表示文件路径。

要追加内容到已经存在的文件中,只需要设置第二个参数为true就行了

  1. FileWriter fstream = new FileWriter(loc, true);  


6、文件复制

只需要调用FileUtils的方法CopyFile(File srcFile, File dstFile),代码如下:

  1. import java.io.IOException;  
  2. import java.nio.file.Files;  
  3. import java.nio.file.Path;  
  4. import java.nio.file.Paths;  
  5.    
  6. public class FileCopyTest {  
  7.     public static void main(String[] args) {  
  8.         Path source = Paths.get("/Users/apple/Desktop/test.rtf");  
  9.         Path destination = Paths.get("/Users/apple/Desktop/copied.rtf");  
  10.    
  11.         try {  
  12.             Files.copy(source, destination);  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         }  
  16.     }  
  17. }  


7、合并文件

  1. package com.programcreek;  
  2.    
  3. import java.io.BufferedReader;  
  4. import java.io.BufferedWriter;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileWriter;  
  8. import java.io.IOException;  
  9. import java.io.InputStreamReader;  
  10.    
  11. public class MergerFiles {  
  12.    
  13.     public static void main(String[] args) {  
  14.         String sourceFile1Path = "/home/programcreek/Desktop/s1";  
  15.         String sourceFile2Path = "/home/programcreek/Desktop/s2";  
  16.    
  17.         String mergedFilePath = "/home/programcreek/Desktop/m";  
  18.    
  19.         File[] files = new File[2];  
  20.         files[0] = new File(sourceFile1Path);  
  21.         files[1] = new File(sourceFile2Path);  
  22.    
  23.         File mergedFile = new File(mergedFilePath);  
  24.    
  25.         mergeFiles(files, mergedFile);  
  26.     }  
  27.    
  28.     public static void mergeFiles(File[] files, File mergedFile) {  
  29.    
  30.         FileWriter fstream = null;  
  31.         BufferedWriter out = null;  
  32.         try {  
  33.             fstream = new FileWriter(mergedFile, true);  
  34.              out = new BufferedWriter(fstream);  
  35.         } catch (IOException e1) {  
  36.             e1.printStackTrace();  
  37.         }  
  38.    
  39.         for (File f : files) {  
  40.             System.out.println("merging: " + f.getName());  
  41.             FileInputStream fis;  
  42.             try {  
  43.                 fis = new FileInputStream(f);  
  44.                 BufferedReader in = new BufferedReader(new InputStreamReader(fis));  
  45.    
  46.                 String aLine;  
  47.                 while ((aLine = in.readLine()) != null) {  
  48.                     out.write(aLine);  
  49.                     out.newLine();  
  50.                 }  
  51.    
  52.                 in.close();  
  53.             } catch (IOException e) {  
  54.                 e.printStackTrace();  
  55.             }  
  56.         }  
  57.    
  58.         try {  
  59.             out.close();  
  60.         } catch (IOException e) {  
  61.             e.printStackTrace();  
  62.         }  
  63.    
  64.     }  
  65. }  


8、移动文件

如果要将文件从一个目录移动另外一个目录下,就用renameTo()方法,下面就是一个例子:

  1. package com.programcreek;  
  2.    
  3. import java.io.File;  
  4.    
  5. public class MoveFileExample {  
  6.    
  7.     public static void main(String[] args) {  
  8.         File file = new File("/home/programcreek/Desktop/s1");  
  9.         String targetDirectory = "/home/programcreek/Desktop/d3/";  
  10.    
  11.         if (file.renameTo(new File(targetDirectory+ file.getName()))) {  
  12.             System.out.println("File is moved to " + targetDirectory);  
  13.         } else {  
  14.             System.out.println("Failed");  
  15.         }  
  16.     }  
  17. }  


9.合并目录

  1. package com.programcreek;  
  2.    
  3. import java.io.File;  
  4.    
  5. public class MergeTwoDirectories {  
  6.     public static void main(String[] args){  
  7.         String sourceDir1Path = "/home/programcreek/Desktop/d1";  
  8.         String sourceDir2Path = "/home/programcreek/Desktop/d2";  
  9.    
  10.         File dir1 = new File(sourceDir1Path);  
  11.         File dir2 = new File(sourceDir2Path);  
  12.    
  13.         mergeTwoDirectories(dir1, dir2);  
  14.    
  15.     }  
  16.    
  17.     public static void mergeTwoDirectories(File dir1, File dir2){  
  18.         String targetDirPath = dir1.getAbsolutePath();  
  19.         File[] files = dir2.listFiles();  
  20.         for (File file : files) {  
  21.             file.renameTo(new File(targetDirPath+File.separator+file.getName()));  
  22.             System.out.println(file.getName() + " is moved!");  
  23.         }  
  24.     }  
  25. }  



10.遍历目录

  1. import java.io.File;  
  2.   
  3. public class Main  
  4. {  
  5.     public static void main(String[] args)  
  6.     {  
  7.         try {  
  8.             File[] files = new File("d:/OJ").listFiles();  
  9.             showFiles(files);  
  10.         } catch (Exception e) {  
  11.               
  12.         }  
  13.     }  
  14.       
  15.     private static void showFiles(File[] files)  
  16.     {  
  17.         for (File file : files) {  
  18.             if (file.isDirectory()) {  
  19.                 System.out.println("Directory:" + file.getName());  
  20.                 showFiles(file.listFiles());  
  21.             } else {  
  22.                 System.out.println("File:" + file.getName());  
  23.             }  
  24.         }  
  25.     }  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值