Java中读取txt文本中内容+目录文件复制到指定目录

时间:2020-11-28 21:01:23

读取txt文本中内容 + 将指定目录文件复制到另一指定目录
俗话说:“好记性不如烂笔头”,还是写写吧。。。

public static void main(String[] args) {
// 读取文件路径
String filePath = "F:\\new5.txt";
readFileTxt(filePath);


//要copy的文件路径
String copyFromUrl = "F:\\aa\\index.jsp";
//copy指定路径
String copyToUrl = "F:\\bb";
File file=new File(copyFromUrl);
if(!file.isDirectory()){
toCopyFile(copyFromUrl,copyToUrl);
}

}
   /**
* 读取txt文本内容
* @param txtUrl TXT路径
* @param toUrl 目标路径
*/

public static void readFileTxt(String txtUrl){
try {
File file =new File(txtUrl);
if(file.isFile()&&file.exists()){
InputStreamReader read=new InputStreamReader(new FileInputStream(file));
BufferedReader br=new BufferedReader(read);
String readLine=null;
//循环打印txt的每一行
while((readLine=br.readLine())!=null){
//去空格
readLine=readLine.trim();
System.out.println(readLine);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}

}
   /**
* 获取指定文件夹下面的所有文件路径并copy
*
* @param file
* 指定文件夹
* @param toUrl
* 目标路径
*/

private static void path1(File file, String toUrl) {
File[] listFiles = file.listFiles();
String classPath;
for (File file2 : listFiles) {
classPath = file2.getAbsolutePath();
if (file2.isDirectory()) {
path1(file2, toUrl);
} else {
// System.out.println("=======" + classPath);
// copy 文件
toCopyFile(classPath,toUrl);

}
}
}
   /**
* 将指定目录下内容复制到指定目录下
* @param txtUrl TAT文档路径
* @param toUrl 目标路径
*/

public static void toCopyFile(String txtUrl,String toUrl){
//txtUrl="F:\\aa\\sdd.txt";

String destPath = toUrl + File.separator + txtUrl.substring(txtUrl.indexOf("aa"));
System.out.println( txtUrl.substring(txtUrl.indexOf("aa")));
System.out.println("目标路径"+destPath);
int end = destPath.lastIndexOf(File.separator);
File file=new File(destPath.substring(0,end));
//判断此文件是否存在,不存在自动创建
if(!file.exists())
file.mkdirs();
System.out.println("目录"+file.getAbsolutePath());
BufferedInputStream bi=null;
BufferedOutputStream bo=null;
try {
bi=new BufferedInputStream(new FileInputStream(txtUrl));
bo=new BufferedOutputStream(new FileOutputStream(destPath));
byte [] data=new byte[2048];
int len;
while((len=bi.read(data))>-1){
bo.write(data, 0, len);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
bo.flush();
bi.close();
bo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}

}