import java.io.*; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class Test { public static void main(String[] args) { File file = new File("D:\\文件.txt"); try { BufferedReader br = new BufferedReader(new FileReader(file));//构造一个BufferedReader类来读取文件 String s = null; while ((s = br.readLine()) != null) {//使用readLine方法,一次读一行 System.out.println(s); //复制文件 File oldFileConf=new File("D:\\https_test.php");//旧文件路径 包括文件名 File newFileConf=new File("D:\\www\\https_test.php");//新文件路径 包括文件名 Files.copy(oldFileConf.toPath(),newFileConf.toPath(), StandardCopyOption.REPLACE_EXISTING);//最后一个参数为如果存在,则覆盖,反之不加则会抛出异常 } } catch (Exception e) { e.printStackTrace(); } } //复制文件夹 public static void filesCopy(Path from, Path to) throws IOException { if(Files.notExists(from)){ System.out.println("源文件夹不存在"); } if(Files.notExists(to)) { Files.createDirectories(to); } Files.walkFileTree(from, new SimpleFileVisitor<Path>() { public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { Path to1 = to.resolve(from.relativize(file)); // 如果说父路径不存在,则创建 if (Files.notExists(to1.getParent())) { Files.createDirectories(to1.getParent()); } Files.copy(file, to1, StandardCopyOption.REPLACE_EXISTING); return FileVisitResult.CONTINUE;//递归遍历文件,空文件无法复制 } }); } //修改文件内容 private static void setText(File fileText,String target,String src) {//修改 BufferedReader br=null; PrintWriter pw=null; StringBuffer buff=new StringBuffer();//临时容器! String line=System.getProperty("line.separator");//平台换行! try { br=new BufferedReader(new FileReader(fileText)); for(String str=br.readLine();str!=null;str=br.readLine()) { if(str.contains(target)) str=str.replaceAll(target,src); buff.append(str+line); } pw=new PrintWriter(new FileWriter(fileText),true); pw.println(buff); } catch (FileNotFoundException e) { e.printStackTrace(); }catch (IOException e) { e.printStackTrace(); }finally { if(br!=null) try { br.close(); } catch (IOException e) { e.printStackTrace(); } if(pw!=null) pw.close(); } } //将一个文件追加到另一个文件末尾 public static void addContent(File target,File newTarget) throws IOException { FileWriter writer = null; try { writer = new FileWriter(newTarget, true); BufferedReader br = new BufferedReader(new FileReader(target));//构造一个BufferedReader类来读取文件 String s = null; while((s = br.readLine())!=null) {//使用readLine方法,一次读一行 // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件 writer.write(s+"\r\n"); } br.close(); } catch (IOException e) { e.printStackTrace(); } finally { try { if(writer != null){ writer.close(); } } catch (IOException e) { e.printStackTrace(); } } } }