【转载】java 文件操作大全(1)
所有代码转载时未经测试
1.创建文件夹
//import java.io.*; File myFolderPath = new File(%%1); try { if (!myFolderPath.exists()) { myFolderPath.mkdir(); } } catch (Exception e) { System.out.println("新建目录操作出错"); e.printStackTrace(); }//import java.io.*; File myFilePath = new File(%%1); try { if (!myFilePath.exists()) { myFilePath.createNewFile(); } FileWriter resultFile = new FileWriter(myFilePath); PrintWriter myFile = new PrintWriter(resultFile); myFile.println(%%2); resultFile.close(); } catch (Exception e) { System.out.println("新建文件操作出错"); e.printStackTrace(); }//import java.io.*; File myDelFile = new File(%%1); try { myDelFile.delete(); } catch (Exception e) { System.out.println("删除文件操作出错"); e.printStackTrace(); }//import java.io.*; File delFolderPath = new File(%%1); try { delFolderPath.delete(); //删除空文件夹 } catch (Exception e) { System.out.println("删除文件夹操作出错"); e.printStackTrace(); }//import java.io.*; File delfile = new File(%%1); File[] files = delfile.listFiles(); for(int i=0; i<files.length; i++) { if(files[i].isDirectory()) { files[i].delete(); } }//import java.io.*; File delfilefolder = new File(%%1); try { if (!delfilefolder.exists()) { delfilefolder.delete(); } delfilefolder.mkdir(); } catch (Exception e) { System.out.println("清空目录操作出错"); e.printStackTrace(); }//import java.io.*; // 逐行读取数据 FileReader fr = new FileReader(%%1); BufferedReader br = new BufferedReader(fr); String %%2 = br.readLine(); while (%%2 != null) { /*TO ADD CODE*/ %%2 = br.readLine(); } br.close(); fr.close();//import java.io.*; // 将数据写入文件 try { FileWriter fw = new FileWriter(%%1); fw.write(%%2); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); }//import java.io.*; try { RandomAcessFile logFile = new RandomAcessFile(%%1,"rw"); long lg = logFile.length(); logFile.seek(%%2); logFile.writeByte(%%3); } catch(IOException ioe) { System.out.println("无法写入文件:"+ioe.getMessage()); }//import java.io.*; // 文件属性的取得 File af = new File(%%1); if (af.exists()) { System.out.println(f.getName() + "的属性如下: 文件长度为:" + f.length()); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目录" : "不是目录"); System.out.println(f.canRead() ? "可读取" : "不"); System.out.println(f.canWrite() ? "是隐藏文件" : ""); System.out.println("文件夹的最后修改日期为:" + new Date(f.lastModified())); } else { System.out.println(f.getName() + "的属性如下:"); System.out.println(f.isFile() ? "是文件" : "不是文件"); System.out.println(f.isDirectory() ? "是目录" : "不是目录"); System.out.println(f.canRead() ? "可读取" : "不"); System.out.println(f.canWrite() ? "是隐藏文件" : ""); System.out.println("文件的最后修改日期为:" + new Date(f.lastModified())); } if(f.canRead()){ %%2 } if(f.canWrite()){ %%3 }//import java.io.*; File filereadonly=new File(%%1); try { boolean b = filereadonly.setReadOnly(); } catch (Exception e) { System.out.println("拒绝写访问:"+e.printStackTrace()); } //import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); while (folderList.size() > 0) { File file = new File(folderList.peek()); folderList.removeLast(); File[] files = file.listFiles(); ArrayList<File> fileList = new ArrayList<File>(); for (int i = 0; i < files.length; i++) { if (files[i].isDirectory()) { folderList.add(files[i].getPath()); } else { fileList.add(files[i]); } } for (File f : fileList) { %%2=f.getAbsoluteFile(); %%3 } }//import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); LinkedList<String> folderList2 = new LinkedList<String>(); folderList2.add(%%2+ %%1.substring(%%1.lastIndexOf("\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.peek()); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); } if (temp.isDirectory()) { // 如果是子文件夹 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); } } } } } catch (Exception e) { //System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); }//import java.io.*; //import java.util.*; File copyfolders=new File(%%1); File[] copyfoldersList = copyfolders.listFiles(); for(int k = 0; k < copyfoldersList.length; k++) { if(copyfoldersList[k].isDirectory()) { ArrayList<String> folderList = new ArrayList<String>(); folderList.add(copyfoldersList[k].getPath()); ArrayList<String> folderList2 = new ArrayList<String>(); folderList2.add(%%2+"/"+copyfoldersList[k].getName()); for(int j = 0; j < folderList.length; j++) { (new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.get(j)); String[] file = folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if (folderList.get(j).endsWith(File.separator)) { temp = new File(folderList.get(j) + "/" + file[i]); } else { temp = new File(folderList.get(j) + "/" + File.separator + file[i]); } FileInputStream input = new FileInputStream(temp); if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.get(j) + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); }//if if (temp.isDirectory()) { //如果是子文件夹 folderList.add(folderList.get(j) + "/" + file[i]); folderList2.add(folderList2.get(j) + "/" + file[i]); } }//for } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } }//for }//if}//for//import java.io.*; //import java.util.*; LinkedList<String> folderList = new LinkedList<String>(); folderList.add(%%1); LinkedList<String> folderList2 = new LinkedList<String>(); folderList2.add(%%2 + %%1.substring(%%1.lastIndexOf("\"))); while (folderList.size() > 0) { (new File(folderList2.peek())).mkdirs(); // 如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.peek()); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.peek().endsWith(File.separator)) { temp = new File(folderList.peek() + File.separator + file[i]); } else { temp = new File(folderList.peek() + File.separator + file[i]); } if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.peek() + File.separator + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ((len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); if (!temp.delete()) { System.out.println("删除单个文件操作出错!"); } }//if if (temp.isDirectory()) {// 如果是子文件夹 for (File f : temp.listFiles()) { if (f.isDirectory()) { folderList.add(f.getPath()); folderList2.add(folderList2.peek() + File.separator + f.getName()); } } } }//for } catch (Exception e) { // System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } folderList.removeFirst(); folderList2.removeFirst(); }//while File f = new File(%%1); if (!f.delete()) { for (File file : f.listFiles()) { if (file.list().length == 0) { System.out.println(file.getPath()); file.delete(); } } }//import java.io.*; //import java.util.*; File movefolders = new File(%%1); File[] movefoldersList = movefolders.listFiles(); for (int k = 0; k < movefoldersList.length; k++) { if (movefoldersList[k].isDirectory()) { ArrayList<String> folderList = new ArrayList<String>(); folderList.add(movefoldersList[k].getPath()); ArrayList<String> folderList2 = new ArrayList<String>(); folderList2.add(%%2 + "/" + movefoldersList[k].getName()); for (int j = 0; j < folderList.length; j++) { (new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.get(j)); String[] file = folders.list(); File temp=null; try { for (int i = 0; i < file.length; i++) { if (folderList.get(j).endsWith(File.separator)) { temp = new File(folderList.get(j) + "/" + file[i]); } else { temp=new File(folderList.get(j) + "/" + File.separator + file[i]); } FileInputStream input = new FileInputStream(temp); if (temp.isFile()) { FileInputStream input = new FileInputStream(temp); FileOutputStream output = new FileOutputStream( folderList2.get(j) + "/" + (temp.getName()).toString()); byte[] b = new byte[5120]; int len; while ( (len = input.read(b)) != -1) { output.write(b, 0, len); } output.flush(); output.close(); input.close(); temp.delete(); }//if if (temp.isDirectory()) {//如果是子文件夹 folderList.add(folderList.get(j) + "/" + file[i]); folderList2.add(folderList2.get(j) + "/" + file[i]); } }//for } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } }//try movefoldersList[k].delete(); }//if }//for//import java.io.*; //import java.util.*; boolean b = false;//不创建空文件 ArrayList<String> folderList = new ArrayList<String>(); folderList.add(%%1); ArrayList<String> folderList2 = new ArrayList<String>(); folderList2.add(%%2); for(int j = 0; j < folderList.length; j++) { (new File(folderList2.get(j))).mkdirs(); //如果文件夹不存在 则建立新文件夹 File folders = new File(folderList.get(j)); String[] file = folders.list(); File temp = null; try { for (int i = 0; i < file.length; i++) { if (folderList.get(j).endsWith(File.separator)) { temp = new File(folderList.get(j) + "/" + file[i]); } else { temp = new File(folderList.get(j) + "/" + File.separator + file[i]); } FileInputStream input = new FileInputStream(temp); if (temp.isFile()) { if (b) { temp.createNewFile(); } } if (temp.isDirectory()) {//如果是子文件夹 folderList.add(folderList.get(j) + "/" + file[i]); folderList2.add(folderList2.get(j) + "/" + file[i]); } }//for } catch (Exception e) { System.out.println("复制整个文件夹内容操作出错"); e.printStackTrace(); } }//for//import java.io.*; int bytesum = 0; int byteread = 0; File oldfile = new File(%%1); try { if (oldfile.exists()) { //文件存在时 FileInputStream inStream = new FileInputStream(oldfile); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); }//import java.io.*; File copyfiles = new File(%%1); File[] files = copyfiles.listFiles(); for (int i = 0; i < files.length; i++) { if (!files[i].isDirectory()) { int bytesum = 0; int byteread = 0; try { InputStream inStream = new FileInputStream(files[i]); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,files[i].getName()); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } }//if }//forString %%2 = %%1.substring(%%1.lastIndexOf(".")+1);String %%2 = %%1.substring(%%1.lastIndexOf("\")+1);String %%2 = %%1.substring(0,%%1.lastIndexOf("\"));//import java.io.*; File replaceExt = new File(%%1); replaceExt.renameTo(replaceExt.getName().split(".")[0] + "." + %%2);final String path = %%1.endsWith("\") ? %%1 : %%1+"\"; %%3=path+%%2;//import java.io.*; int bytesum = 0; int byteread = 0; File oldfile = new File(%%1); try { if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldfile); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 //System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); oldfile.delete(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); }//import java.io.*; File movefile = new File(%%1); File[] movefiles = movefile.listFiles(); for (int i = 0; i < movefiles.length; i++) { if (movefiles[i].isFile()) { int bytesum = 0; int byteread = 0; File oldfile = new File(movefiles[i]); try { if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldfile); //读入原文件 FileOutputStream fs = new FileOutputStream(new File(%%2,oldfile.getName())); byte[] buffer = new byte[5120]; int length; while ( (byteread = inStream.read(buffer)) != -1) { bytesum += byteread; //字节数 文件大小 //System.out.println(bytesum); fs.write(buffer, 0, byteread); } inStream.close(); oldfile.delete(); } } catch (Exception e) { System.out.println("复制单个文件操作出错"); e.printStackTrace(); } }//if }//for//import java.io.*; String filter = "*.*"; String path = %%1; File file = new File(path); if (file.exists()) { if (file.isDirectory()) { File[] fileArray = file.listFiles(); for (File f:fileArray) { if (f.isDirectory()) { doSearch(filter,f.getPath()); } else { if (f.getName().indexOf(filter) >= 0) { countFiles++; result.append(f.getPath() + "\r\n"); } } statusShow1.setText(f.getPath()); } statusShow2.setText("The numbers of files had been found:" + countFiles); } else { System.out.println("Couldn't open the path!"); } } else { System.out.println("The path had been apointed was not Exist!"); }//import java.io.*; //import javax.swing.*; JFileChooser Jfc = new JFileChooser(); //建立选择档案对话方块盒 Jfc if (Jfc.isFileSelectionEnabled()) { File %%1 = Jfc.getSelectedFile(); }//import java.io.* try { File f = new File(%%1); FileInputStream fileInputStream = new FileInputStream(f); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); String strFileName = f.getName(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2 + "\" + strFileName + "1")); fileOutputStream.write(buffer,0,buffer.length/2); fileOutputStream.close(); fileOutputStream = new FileOutputStream(new File(%%2 + "\" + strFileName + "2")); fileOutputStream.write(buffer, buffer.length/2, buffer.length-buffer.length/2); fileOutputStream.close(); } catch (ArrayIndexOutOfBoundsException e) { System.out.print("using FileStreamDemo src des"); e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }//import java.io.* String strFileName = %%1.substring(%%1.LastIndexOf("\") + 1); try { FileInputStream fileInputStream1 = new FileInputStream(new File(%%2 + strFileName + "1")); FileInputStream fileInputStream2 = new FileInputStream(new File(%%2 + strFileName + "2")); byte[] buffer = new byte[fileInputStream1.available() + fileInputStream2.available()]; FileInputStream.read(buffer, 0, fileInputStream1.available()); FileInputStream2.read(buffer, fileInputStream1.available(), fileInputStream2.available()); fileInputStream.close(); fileInputStream2.close(); FileOutputStream fileOutputStream = new FileOutputStream(new File(%%2 + "\" + strFileName)); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(IOException e) { e.printStackTrace(); }//import java.io.* try { File f=new File((new File(%%1)).getPath() + "\\enc_" + (new File(%%1)).getName().split("//")[1]); String strFileName = f.getName(); FileInputStream fileInputStream = new FileInputStream(%%2 + "\" + strFilename); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for (int i = 0; i < buffer.length; i++) { int ibt = buffer[i]; ibt += 100; ibt %= 256; buffer[i] = (byte)ibt; } FileOutputStream fileOutputStream = new FileOutputStream(f); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(ArrayIndexOutOfBoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }//import java.io.* try { File f = new File(%%1); String strFileName = f.getName(); FileInputStream fileInputStream = new FileInputStream(%%2 + "\\enc_" + strFilename); byte[] buffer = new byte[fileInputStream.available()]; FileInputStream.read(buffer); fileInputStream.close(); for (int i = 0; i < buffer.length; i++) { int ibt = buffer[i]; ibt -= 100; ibt += 256; ibt %= 256; buffer[i] = (byte)ibt; } FileOutputStream fileOutputStream = new FileOutputStream(f); fileOutputStream.write(buffer,0,buffer.length); fileOutputStream.close(); } catch(ArrayIndexOutOfBoundException e) { e.printStackTrace(); } catch(IOException e) { e.printStackTrace(); }//import java.io.*; //import java.util.*; //import java.util.regex.*; if (configMap == null) { String WriteBuffer = ""; configMap = new HashMap<String, Serializable>(); String strLine = null; String currentNode = null; String previousNode = null; Vector<Properties> vec = new Vector<Properties>(); int row = 0; FileReader fileReader = null; try { fileReader = new FileReader("Config.ini"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader bufferedReader = new BufferedReader(fileReader); try { while ((strLine = bufferedReader.readLine()) != null) { String oneLine = strLine.trim(); if (oneLine.length() >= 1) { Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]"); int nodelen = oneLine.split("[;]").length; String[] strArray1 = new String[4]; if (nodelen == 1) { oneLine = oneLine.split("[;]")[0].trim(); } else if (nodelen == 2) { strArray1[3] = oneLine.split("[;]")[1].trim(); oneLine = oneLine.split("[;]")[0].trim(); } Matcher m = p.matcher(oneLine); if (m.matches()) { strArray1[0] = "@Node"; strArray1[1] = oneLine; strArray1[2] = ""; } else { int keylen = oneLine.split("=").length; if (keylen == 1) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = ""; } else if (keylen == 2) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = oneLine.split("=")[1]; } else { strArray1[0] = "@ElementError"; strArray1[1] = ""; strArray1[2] = ""; strArray1[3] = ""; } }//else if (strArray1[0].equals("@Node")) { previousNode = currentNode; currentNode = strArray1[1]; if (row > 0) { configMap.put(previousNode, vec.elementAt(0)); vec.clear(); row = 0; } WriteBuffer += (oneLine + "\r\n"); } else if (strArray1[0].equals("@Key") && row == 0) { Properties ht = new Properties(); ht.setProperty(strArray1[1], strArray1[2]); if (strArray1[1].equals(%%1)) { WriteBuffer += (%%1 + "=" + %%2 + "\r\n"); } else { WriteBuffer += (oneLine + "\r\n"); vec.add(0, ht); row++; } } else if (strArray1[0].equals("@Key") && row > 0) { Properties ht2 = new Properties(); ht2.put(strArray1[1], strArray1[2]); vec.clear(); vec.add(0, ht2); WriteBuffer += (oneLine + "\r\n"); row++; } }//if }//while configMap.put(currentNode, vec.elementAt(0)); } catch (FileNotFoundException e) { configMap = null; e.printStackTrace(); } catch (IOException e) { configMap = null; e.printStackTrace(); } finally { vec.clear(); try { bufferedReader.close(); fileReader.close(); } catch (IOException e) { e.printStackTrace(); } try { FileWriter fw = new FileWriter("Config.ini"); fw.write(WriteBuffer); fw.flush(); fw.close(); } catch (IOException e) { e.printStackTrace(); } } }//if//import java.io.*; //import java.util.*; //import java.util.regex.*; //private HashMap configMap=null; private Map<String, Serializable> configMap = null; String %%2 = null; if (configMap == null) { configMap = new HashMap<String, Serializable>(); String strLine = null; String currentNode = null; String previousNode = null; Vector<Properties> vec = new Vector<Properties>(); int row = 0; FileReader fileReader = null; try { fileReader = new FileReader("Config.ini"); } catch (FileNotFoundException e1) { e1.printStackTrace(); } BufferedReader bufferedReader = new BufferedReader(fileReader); try { while ((strLine = bufferedReader.readLine()) != null) { String oneLine = strLine.trim(); if (oneLine.length() >= 1) { Pattern p = Pattern.compile("\\[\\s*.*\\s*\\]"); int nodelen = oneLine.split("[;]").length; String[] strArray1 = new String[4]; if (nodelen == 1) { oneLine = oneLine.split("[;]")[0].trim(); } else if (nodelen == 2) { strArray1[3] = oneLine.split("[;]")[1].trim(); oneLine = oneLine.split("[;]")[0].trim(); } Matcher m = p.matcher(oneLine); if (m.matches()) { strArray1[0] = "@Node"; strArray1[1] = oneLine; strArray1[2] = ""; } else { int keylen = oneLine.split("=").length; if (keylen == 1) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = ""; } else if (keylen == 2) { strArray1[0] = "@Key"; strArray1[1] = oneLine.split("=")[0]; strArray1[2] = oneLine.split("=")[1]; } else { strArray1[0] = "@ElementError"; strArray1[1] = ""; strArray1[2] = ""; strArray1[3] = ""; } }//else if (strArray1[0].equals("@Node")) { previousNode = currentNode; currentNode = strArray1[1]; if (row > 0) { configMap.put(previousNode, vec.elementAt(0)); vec.clear(); row = 0; } } else if (strArray1[0].equals("@Key") && row == 0) { Properties ht = new Properties(); ht.setProperty(strArray1[1], strArray1[2]); if (strArray1[1].equals(%%1)) { %%2 = strArray1[2]; return; } vec.add(0, ht); row++; } else if (strArray1[0].equals("@Key") && row > 0) { Properties ht2 = new Properties(); ht2.put(strArray1[1], strArray1[2]); vec.clear(); vec.add(0, ht2); row++; } }//if }//while configMap.put(currentNode, vec.elementAt(0)); } catch (FileNotFoundException e) { configMap = null; e.printStackTrace(); } catch (IOException e) { configMap = null; e.printStackTrace(); } finally { vec.clear(); try { bufferedReader.close(); fileReader.close(); } catch (IOException e) { e.printStackTrace(); } } }//if