Java8各種文件操作(刪除、讀寫、拷貝)總結

maven項目讀取Resource文件夾裏面文件

//check.txt文件路徑爲Resource/dict/check.txt
Resource classPathResource = new ClassPathResource("dict/check.txt"); 
File f = classPathResource.getFile();
//這種方法好像項目打成jar包後就不管用了

文件操作

BIO

1. 按字節讀取文件內容

/**
 * 以字節爲單位讀取文件,常用於讀二進制文件,如圖片、聲音、影像等文件。
 *
 * @param fileName 文件的名
 */
public static void readFileByBytes(String fileName) {
	File file = new File(fileName);
	InputStream in = null;
	try {
		System.out.println("以字節爲單位讀取文件內容,一次讀一個字節:");
		// 一次讀一個字節
		in = new FileInputStream(file);
		int tempbyte;
		while ((tempbyte = in.read()) != -1) {
			System.out.write(tempbyte);
		}
		in.close();
	} catch (IOException e) {
		e.printStackTrace();
		return;
	}
	try {
		System.out.println("以字節爲單位讀取文件內容,一次讀多個字節:");
		//一次讀多個字節
		byte[] tempbytes = new byte[100];
		int byteread = 0;
		in = new FileInputStream(fileName);
		ReadFromFile.showAvailableBytes(in);
		//讀入多個字節到字節數組中,byteread爲一次讀入的字節數
		while ((byteread = in.read(tempbytes)) != -1) {
			System.out.write(tempbytes, 0, byteread);
		}
	} catch (Exception e1) {
		e1.printStackTrace();
	} finally {
		if (in != null) {
			try {
				in.close();
			} catch (IOException e1) {
			}
		}
	}
}

2. 按字符讀取文件內容

/**
 * 以字符爲單位讀取文件,常用於讀文本,數字等類型的文件
 *
 * @param fileName 文件名
 */
public static void readFileByChars(String fileName) {
	File file = new File(fileName);
	Reader reader = null;
	try {
		System.out.println("以字符爲單位讀取文件內容,一次讀一個字節:");
		// 一次讀一個字符
		reader = new InputStreamReader(new FileInputStream(file));
		int tempchar;
		while ((tempchar = reader.read()) != -1) {
		//對於windows下,rn這兩個字符在一起時,表示一個換行。
		//但如果這兩個字符分開顯示時,會換兩次行。
		//因此,屏蔽掉r,或者屏蔽n。否則,將會多出很多空行。
			if (((char) tempchar) != 'r') {
				System.out.print((char) tempchar);
			}
		}
		reader.close();
	} catch (Exception e) {
		e.printStackTrace();
	}
	try {
		System.out.println("以字符爲單位讀取文件內容,一次讀多個字節:");
		//一次讀多個字符
		char[] tempchars = new char[30];
		int charread = 0;
		reader = new InputStreamReader(new FileInputStream(fileName));
		//讀入多個字符到字符數組中,charread爲一次讀取字符數
		while ((charread = reader.read(tempchars)) != -1) {
			//同樣屏蔽掉r不顯示
			if ((charread == tempchars.length) && (tempchars[tempchars.length - 1] != 'r')) {
				System.out.print(tempchars);
			} else {
				for (int i = 0; i < charread; i++) {
					if (tempchars[i] == 'r') {
						continue;
					} else {
						System.out.print(tempchars[i]);
					}
				}
			}
		}
	} catch (Exception e1) {
		e1.printStackTrace();
	} finally {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e1) {
			}
		}
	}
}

3. 按行讀取文件內容

/**
 * 以行爲單位讀取文件,常用於讀面向行的格式化文件
 *
 * @param fileName 文件名
 */
public static void readFileByLines(String fileName) {
	File file = new File(fileName);
	BufferedReader reader = null;
	try {
		System.out.println("以行爲單位讀取文件內容,一次讀一整行:");
		reader = new BufferedReader(new FileReader(file));
		String tempString = null;
		int line = 1;
		//一次讀入一行,直到讀入null爲文件結束
		while ((tempString = reader.readLine()) != null) {
			//顯示行號
			System.out.println("line " + line + ": " + tempString);
			line++;
		}
		reader.close();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (reader != null) {
			try {
				reader.close();
			} catch (IOException e1) {
			}
		}
	}
}

4. 隨機讀取文件內容

/**
 * 隨機讀取文件內容
 *
 * @param fileName 文件名
 */
public static void readFileByRandomAccess(String fileName) {
	RandomAccessFile randomFile = null;
	try {
		System.out.println("隨機讀取一段文件內容:");
		// 打開一個隨機訪問文件流,按只讀方式
		randomFile = new RandomAccessFile(fileName, "r");
		// 文件長度,字節數
		long fileLength = randomFile.length();
		// 讀文件的起始位置
		int beginIndex = (fileLength > 4) ? 4 : 0;
		//將讀文件的開始位置移到beginIndex位置。
		randomFile.seek(beginIndex);
		byte[] bytes = new byte[10];
		int byteread = 0;
		//一次讀10個字節,如果文件內容不足10個字節,則讀剩下的字節。
		//將一次讀取的字節數賦給byteread
		while ((byteread = randomFile.read(bytes)) != -1) {
			System.out.write(bytes, 0, byteread);
		}
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		if (randomFile != null) {
			try {
				randomFile.close();
			} catch (IOException e1) {
			}
		}
	}
}

5. 寫文件

方法一

/**
 * A方法追加文件:使用RandomAccessFile
 *
 * @param fileName 文件名
 * @param content  追加的內容
 */
public static void appendMethodA(String fileName, String content) {
	try {
		// 打開一個隨機訪問文件流,按讀寫方式
		RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
		// 文件長度,字節數
		long fileLength = randomFile.length();
		//將寫文件指針移到文件尾。
		randomFile.seek(fileLength);
		randomFile.writeBytes(content);
		randomFile.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

方法二

/**
 * B方法追加文件:使用FileWriter
 *
 * @param fileName
 * @param content
 */
public static void appendMethodB(String fileName, String content) {
	try {
		//打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件
		FileWriter writer = new FileWriter(fileName, true);
		writer.write(content);
		writer.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
}

NIO

參考API
參考文章

Path

path接口是在java7加入到NIO的,位於java.nio.file包,它的實例代表了文件系統裏的一個路徑,可以指向文件或文件夾

初始化
Path path = Paths.get("D:\\svn-config.properties");
Path.normalize()

normalize()方法可以標準化一個路徑,就是移除掉所有在路徑字符中的的 . 和 …,同時決定路徑字符串指向哪條路徑。

Path path = Paths.get("D:\\Users\\xxx\\Desktop\\..\\svn-config.properties");
Path path1 = path.normalize();
System.out.println(path);
System.out.println(path1);

//輸出結果
//D:\Users\xxx\Desktop\..\svn-config.properties
//D:\Users\xxx\svn-config.properties 

Files類

Files類位於nio.file包中,提供了幾個熟練的文件操作

判斷文件存在

LinkOption.NOFOLLOW_LINKS 表明判斷文件存在的方法不應該根據文件系統中的符號連接來判斷路徑是否存在

Path path = Paths.get("D:\\Users\\xxx\\Desktop\\svn-config.properties");
boolean isExist = Files.exists(path, LinkOption.NOFOLLOW_LINKS);
創建文件夾
Path path = Paths.get("D:\dir");
try 
{
    Path newDir = Files.createDirectory(path);
} catch(FileAlreadyExistsException e){
    // the directory already exists.
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}
拷貝文件
Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties");

try {
    Files.copy(sourcePath, destinationPath);
} catch(FileAlreadyExistsException e) {
    //destination file already exists
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}
覆蓋文件
Path sourcePath      = Paths.get("data/logging.properties");
Path destinationPath = Paths.get("data/logging-copy.properties");

try {
    Files.copy(sourcePath, destinationPath,
            StandardCopyOption.REPLACE_EXISTING);
} catch(FileAlreadyExistsException e) {
    //destination file already exists
} catch (IOException e) {
    //something else went wrong
    e.printStackTrace();
}
移動文件
Path sourcePath      = Paths.get("data/logging-copy.properties");
Path destinationPath = Paths.get("data/subdir/logging-moved.properties");

try {
    Files.move(sourcePath, destinationPath,StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
    //moving file failed.
    e.printStackTrace();
}
刪除文件
Path path = Paths.get("data/subdir/logging-moved.properties");
try {
    Files.delete(path);
} catch (IOException e) {
    //deleting file failed
    e.printStackTrace();
}
遍歷文件夾
Path path = Paths.get("D:\\mnt");
Files.walkFileTree(path, new FileVisitor<Path>() {
    @Override
    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
        System.out.println("pre visit dir:" + dir);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        System.out.println("visit file: " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
        System.out.println("visit file failed: " + file);
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
        System.out.println("post visit directory: " + dir);
        return FileVisitResult.CONTINUE;
    }
});
查找文件
 Path root = Paths.get("D:\\mnt");
 final String fileToFind = File.separator+"path.txt";
 try {
     Files.walkFileTree(root, new SimpleFileVisitor<Path>() {

         @Override
         public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
             String fileString = file.toAbsolutePath().toString();
             //System.out.println("pathString = " + fileString);

             if(fileString.endsWith(fileToFind)){
                 System.out.println("file found at path: " + file.toAbsolutePath());
                 return FileVisitResult.TERMINATE;
             }
             return FileVisitResult.CONTINUE;
         }
     });
 } catch(IOException e){
     e.printStackTrace();
 }
循環刪除文件
Path rootPath = Paths.get("data/to-delete");

try {
  Files.walkFileTree(rootPath, new SimpleFileVisitor<Path>() {
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
      System.out.println("delete file: " + file.toString());
      Files.delete(file);
      return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException {
      Files.delete(dir);
      System.out.println("delete dir: " + dir.toString());
      return FileVisitResult.CONTINUE;
    }
  });
} catch(IOException e){
  e.printStackTrace();
}
生成超鏈接
//連接路徑
 Path p = Paths.get("D:\\mnt\\1.txt");
 //目標路徑
 Path target = Paths.get("D:\\Users\\weizhiming\\Desktop");
 //生成指向目標路徑的超鏈接,返回連接路徑p
 Path p3 = Files.createSymbolicLink(p,target);
讀取文件內容
//讀取每行數據放入List中
List<String> lines = Files.readAllLines(Paths.get("d://a.txt"));
//讀取文件內容放入流中
Stream<String> lines = Files.lines(Paths.get("d://a.txt"));

上面的例子要注意幾點:

  1. 文件可能很大,可能會超出內存空間,使用前要做評估。
  2. 要輸出日誌,記錄爲什麼無法讀取文件或者在閱讀文件時遇到的任何錯誤。
  3. 在把字節轉換成字符時,應該指定字符編碼。
  4. 要處理文件不存在的情況。
所有方法(java8)

在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
在這裏插入圖片描述
參考鏈接

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章