初学JAVA:创建/删除/读取/复制文档、文件夹等操作

//面对自己曾经想要进行文档有关的操作还要去百度的麻烦,特意整理写了这篇文章,方便自己也方便大家
//创建的包名叫com.hyon,class类名叫AboutFile,创建的时候记得注意
//此文件我实在JDK1.8的情况下运行的,不确保其他版本不会出现BUG
//此文档所用方法较为简单,适合于初学者学习使用
//切勿同时调用所有方法,必报错,需要测试哪个方法即调用哪个
//如果你在使用过程中遇到什么问题,欢迎留言


package com.hyon;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.RandomAccessFile;
import java.io.UnsupportedEncodingException;


public class AboutFile {
	public static void main(String[] args) throws IOException{
		new AboutFile();
	}
	
	private AboutFile() throws IOException {
		//需要哪个方法则调用哪个,若同时调用会报错,有些文件需要自己在D盘里创建后才能看到效果,比如MyDir文件夹和666文件夹
//		CreateFile();//调用创建文件方法
//		CreateDrectory();//调用创建文件夹方法
//		CreateTmpFile();//调用创建临时文件夹方法
//		ReadFile();//调用读取文档内容方法
//		WriteFile();//调用写入文档内容方法
//		simpleDeleteFile();//调用文档删除方法
//		complexDeleteFiles(new File("d:/MyDir"));//调用删除该文件夹下所有文件的方法
//		ReadCnFile();
//		deleteDirectory(new File("d:/MyDir"));//调用删除该文件夹的方法
//		startCopy("d:/666","d:/66");//调用复制一个文件夹包含里面所有文件的方法
	}

private void startCopy(String sourceFile,String targetFile) {
		//开始复制文件夹
		(new File(targetFile)).mkdirs();
		File[] file = (new File(sourceFile)).listFiles();
		//对文件夹目录下的每一个文件进行判断是文件还是文件夹
		for (int i = 0; i < file.length; i++) {
			//先判断是否为文件,若是,则开始复制文件
			if (file[i].isFile()) {
				FileInputStream input;
				try {
					input = new FileInputStream(file[i]);
					FileOutputStream output = new FileOutputStream(targetFile + "/" +file[i].getName());
					byte[] b = new byte[1024*5];
					int len;
					try {
						while ((len = input.read(b))!=-1) output.write(b,0,len);
						output.flush();
						output.close();
						input.close();
					} catch (IOException e1) {
						// TODO: handle exception
						e1.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
				//判断是否为文件夹,若是,则调用复制文件夹函数
				if (file[i].isDirectory()) copyDirectiory 
				(targetFile+"/"+file[i].getName(),sourceFile+"/"+file[i].getName());
		}
		
	}


	private void copyDirectiory(String file1, String file2) {
	// 将源文件夹下的文件复制到目标文件夹
		(new File(file1)).mkdirs();
		File[] file = (new File(file2)).listFiles();
		for (int i = 0; i < file.length; i++) {
			//先判断子文件夹下是否为文件,若是,则开始复制文件
			if (file[i].isFile()) {
				System.out.println("是否存在子目录"+file[i]);
				FileInputStream input;
				try {
					input = new FileInputStream(file[i]);
					FileOutputStream output = new FileOutputStream(file1 + "/" + file[i].getName());
					byte[] b = new byte[1024*5];
					int len;
					try {
						while ((len = input.read(b))!=-1) output.write(b,0,len);
						output.flush();
						output.close();
						input.close();
					} catch (IOException e1) {
						// TODO: handle exception
						e1.printStackTrace();
					}
				} catch (FileNotFoundException e) {
					// TODO: handle exception
					e.printStackTrace();
			}
			}
			//判断子文件夹是否为文件夹,若是,则调用复制文件夹函数
			if (file[i].isDirectory()) copyDirectiory 
			(file1 +"/"+ file[i].getName(),file2+"/"+file[i].getName());
			System.out.println("是否存在子目录"+file[i]);
			
		}
	
}

	private void deleteDirectory(File dir) {
		// 删除该文件夹
		if((dir == null)||!dir.isDirectory()) throw new IllegalArgumentException
		("Argument" + dir + "is not a directiry.");
		File[] entries = dir.listFiles();
		int sz = entries.length;
		for (int i = 0; i < entries.length; i++) {
			if (entries[i].isDirectory()) deleteDirectory(entries[i]); 
			else entries[i].delete();
		}
		dir.delete();
	}

	private void ReadCnFile() {
		// TODO Auto-generated method stub
		//读取有汉字的文档
		StringBuffer sb = getFileCNComtent("d:/sample.txt",getEntrySymbol());
		System.out.println(sb.toString());
	}


	private StringBuffer getFileCNComtent(String filename, String enter) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		File f = new File(filename);
		if (f.isFile()&&f.exists()) {
			InputStreamReader read;
			try {
				read = new InputStreamReader(new FileInputStream(f),"GBK");
				BufferedReader reader = new BufferedReader(read);
				String line;
				while ((line = reader.readLine())!=null)sb.append(line).append(enter);
				read.close();
			} catch (UnsupportedEncodingException e) {
				// TODO: handle exception
				e.printStackTrace();
			}catch (FileNotFoundException e) {
				// TODO: handle exception
				e.printStackTrace();
			}catch (IOException e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}
		return sb;
	}

	private String getEntrySymbol() {
		// TODO Auto-generated method stub
		
		String os = System.getProperty("os.name").toLowerCase();
		String enterSymbol = "";//换行符号
		if (os.indexOf("win")>=0)enterSymbol = "\r\n";
		else if(os.indexOf("mac")>=0)enterSymbol = "\r";
		else if(os.indexOf("nix")>=0 || os.indexOf("nux")>=0)enterSymbol = "\n";
		return enterSymbol;
	}

	private void complexDeleteFiles(File directory) {
		// 删除该文件夹下所有文件
		File[] entries = directory.listFiles();
		for (int i = 0; i < entries.length; i++) {
			entries[i].delete();
		}
		System.out.println("all files are deleted");
	}

	private void simpleDeleteFile() {
		// 删除d:/sample.txt文件
		File file = new File("d:/sample.txt");
		if (file.exists() && file.canWrite()) {
			file.delete();
			System.out.println("deleted");
		}
	}

	private void WriteFile() throws IOException{
		// 向d:/sample.txt文档内写入内容
		
		//第一种方法
		BufferedWriter bw1 = new BufferedWriter(
				new OutputStreamWriter(new FileOutputStream(new File("d:/sample.txt"))));
		bw1.write("111111111111");
		bw1.close();
		
		//第二种方法,会删除之前所有内容
		BufferedWriter bw2 = new BufferedWriter(
				new FileWriter(new File("d:/sample.txt")));
		bw2.write("222222222222");
		bw2.close();
		
		//第三种方法,此方法无法写入汉字,并且会删除之前所有内容
		DataOutputStream dos = new DataOutputStream(
				new FileOutputStream(new File("d:/sample.txt")));
		dos.writeBytes("333333333333");
		dos.close();
		
		//第四种方法,此方法无法写入汉字
		RandomAccessFile raf = new RandomAccessFile(new File("d:/sample.txt"), "rw");
		raf.seek(raf.length());
		raf.writeBytes("44444444444444");
		raf.close();
		
	}

	private void ReadFile() throws IOException{
		// 读取d:/sample.txt这个文件里的文本
		
		//第一种方法
		System.out.println("Reader function1:");
		BufferedReader br1 = new BufferedReader(
				new FileReader(new File("d:/sample.txt")));
		while (br1.ready()) {
			System.out.println(br1.readLine());	
		}
		
		//第二种方法
		System.out.println("Reader function2:");
		BufferedReader br2 = new BufferedReader(
				new InputStreamReader(new FileInputStream(new File("d:/sample.txt"))));
		while (br2.ready()) {
			System.out.println(br2.readLine());
		}
		
		//第三种方法
		System.out.println("Reader function3:");
		DataInputStream dis = new DataInputStream(
				new FileInputStream(new File("d:/sample.txt")));
		//调用一行行读取方法进行读取
		DowhileReaderLine(dis,null);
		
	}

	private void DowhileReaderLine(DataInputStream dis, RandomAccessFile raf) throws IOException{
		// 将文档一行行进行读取
		
		//RandomAccessFile的工作方式是,把DataInputStream和DataOutputStream粘起来,再加上它自己的一些方法
		//DataInputStream据输入流允许应用程序
		
		String tmp = "";
		if (dis != null) {
			System.out.println("the obj is DataInputStream");
		} else {
			System.out.println("the obj is RandomAccessFile");
		}
		while (true) {
			if (dis != null) {
				tmp=dis.readLine();
			} else {
				tmp=raf.readLine();
			}if (tmp!=null) {
				System.out.println(tmp);
			} else {
				break;
			}
		}
	
		
	}

	private void CreateTmpFile()throws IOException {
		
		//创建一个临时文件
		
		File tmpFile = File.createTempFile("~template", "tmp");
		
		try {
		}catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			
		} finally {
			// TODO: handle finally clause
			tmpFile.deleteOnExit();
		}
	}

	private void CreateDrectory()throws IOException {
		//创建文件夹的方法
		File f3 = new File("d:/MyDir");
		f3.mkdir();
	}

	private void CreateFile()throws IOException {
		
		//创建文件的三种方法
		
		//第一种,新建一个对象,填入文件及路径,然后进行判断,若为true则创建,false则不创建
		File f1 = new File("d:/myfile1.txt");
		Judgement(f1);
		
		//第二种,新建一个对象,分开填入文件及路径,然后进行判断,若为true则创建,false则不创建
		File f2 = new File("d:", "myfile2.txt");
		Judgement(f2);
		
		//第三种,通过创建输出流方式创建文件
		FileOutputStream fot = new FileOutputStream("d:/myfile3.txt");
	}

	private void Judgement(File f)throws IOException {
		// TODO Auto-generated method stub
		if (!f.createNewFile()) {
			System.out.println(f.getName() + "has already exist!!!");
		} else {
			System.out.println(f.getName() + "is created");
		}
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

print_Hyon

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值