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

来源:互联网 发布:第三方支付平台 知乎 编辑:程序博客网 时间:2024/06/05 06:34
//面对自己曾经想要进行文档有关的操作还要去百度的麻烦,特意整理写了这篇文章,方便自己也方便大家//创建的包名叫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 exceptione1.printStackTrace();}} catch (FileNotFoundException e) {// TODO: handle exceptione.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 exceptione1.printStackTrace();}} catch (FileNotFoundException e) {// TODO: handle exceptione.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 stubStringBuffer 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 exceptione.printStackTrace();}catch (FileNotFoundException e) {// TODO: handle exceptione.printStackTrace();}catch (IOException e) {// TODO: handle exceptione.printStackTrace();}}return sb;}private String getEntrySymbol() {// TODO Auto-generated method stubString 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 exceptione.printStackTrace();} finally {// TODO: handle finally clausetmpFile.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 stubif (!f.createNewFile()) {System.out.println(f.getName() + "has already exist!!!");} else {System.out.println(f.getName() + "is created");}}}

阅读全文
0 0