Java io詳解(二)-File

     這裏我們開始講io流,其實io流的本質就是對文件的操作。這裏我講解的方式主要是以代碼的形式來講解的,因爲編程這東西,看的懂不一定敲的出來

一定要自己親自敲了 纔會知道怎麼用的

 下面的代碼中列出了java io File類的主要方法:

package org.io.file.demo;

import java.io.File;
import java.io.IOException;

public class DemoFile {

	/**
	 * 判斷文件目錄或者指定文件是否存在
	 * @param file 已經加載指定路徑的file對象
	 * @return 假如存在返回 true 否則返回 flase
	 */
	public boolean exists(File file){
		boolean b = file.exists();
		return b;
	}
	
	/**
	 * 創建指定目錄
	 * @param file 已經加載指定路徑的file對象
	 * @return 如果創建成功返回 true 否則返回 false
	 */
	public boolean createFolderPath(File file){
		boolean b = file.mkdirs();
		return b;
	}
	
	/**
	 * 創建指定文件
	 * @param file 已經加載指定路徑的file對象
	 * @return 如果創建成功返回 true 否則返回 false
	 */
	public boolean createFile(File file){
		boolean b = false;
		try {
			b = file.createNewFile();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return b;
	}
	
	/**
	 * 創建制定目下的指定文件
	 * @param folderPath 指定目錄
	 * @param fileName 指定文件
	 */
	public void createMyFile(String folderPath , String fileName){
		File file = new File(folderPath);
		boolean b = false;
		b = this.exists(file);
		if(b){
			file = new File(folderPath + fileName);
			b = this.createFile(file);
		}else{
			b = this.createFolderPath(file);
			file = new File(folderPath + fileName);
			b = this.createFile(file);
		}
		
		if(b){
			System.out.println("operation success !");
		}else{
			System.out.println("operation fail !");
		}
	}
	
	public static void main(String[] args) {
		String folderPath = "src/myFile/";
		String fileName = "Hello.txt";
		DemoFile demoFile = new DemoFile();
		demoFile.createMyFile(folderPath, fileName);
	}
}


好了 Java io 對文件的處理就到這裏了,有什麼不懂的  可以了問我  因爲我也是剛學不久 大家一起啊進步

 

發佈了34 篇原創文章 · 獲贊 55 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章