java-file
1.递归调取文件夹下所有文件(包含子目录)
public static void getAllFile(File file){ File[] files = file.listFiles(); for(File f:files) { if(f.isDirectory()) { getAllFile(f); }else { System.err.println("获取文件地址:"+f); } } }
2.调取文件夹下所有文件(不包含子目录)
public static List<String> getAllFileName(String path) { File file = new File(path); File[] tempList = file.listFiles(); List<String> fileNameList = new ArrayList<String>(); for (int i = 0; i < tempList.length; i++) { if (tempList[i].isFile()) { fileNameList.add(tempList[i].getName()); } } return fileNameList; }
3.读取文件文件名
public static String readFileContent(String fileName) throws IOException { List<String> lines=new ArrayList<String>(); BufferedReader br=new BufferedReader(new InputStreamReader(new FileInputStream(fileName),"UTF-8")); String line = null; while ((line = br.readLine()) != null) { lines.add(line); } br.close(); String result = ""; for (String string : lines) { result = string; } return result; }
4.实现文件的剪切
public static void showCut(String path,String outPath,String context) throws IOException { String result = readFileContent(path); String txtName = path.substring(path.lastIndexOf("/"), path.length()); File dir = new File(outPath); if (!dir.exists()) { dir.mkdirs(); } File checkFile = new File(outPath +"/"+txtName); FileWriter writer = null; try { if (!checkFile.exists()) { } writer = new FileWriter(checkFile, true); writer.append(result); writer.flush(); File f = new File(path); Del(f); createFile(context); } catch (IOException e) { e.printStackTrace(); } finally { if (null != writer) writer.close(); } } /** * 复制完成后删除文件 */ public static void Del(File f) { if (f.isFile()) { f.delete(); } else { File[] arr = f.listFiles(); for (int i = 0; i < arr.length; i++) { Del(arr[i]); } f.delete(); } }
5.写入文件
public static void createFile(String content) throws IOException { File dir = new File(logfile); if (!dir.exists()) { dir.mkdirs(); } Date date = new Date(); SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd"); String strTime = simpleDateFormat.format(date); File checkFile = new File(logfile +"logs_"+strTime+".txt"); FileWriter writer = null; try { if (!checkFile.exists()) { } writer = new FileWriter(checkFile, true); writer.append(content); writer.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (null != writer) writer.close(); } }