Java java지도 시간 자바 파일 및 디렉토리의 추가, 삭제, 복사에 대한 자세한 설명

자바 파일 및 디렉토리의 추가, 삭제, 복사에 대한 자세한 설명

Jul 02, 2017 am 10:21 AM
java 복사

이 글에서는 주로 Java 파일과 디렉토리의 추가, 삭제, 복사에 대해 자세히 소개하고 있으니 참고할만한 가치가 있으니 관심있는 친구들이 참고하면 됩니다.

Java를 사용하여 개발할 때 파일과 디렉토리의 추가와 삭제를 자주 사용합니다. 복사 및 기타 방법. 위젯 클래스를 작성했습니다. 모든 사람과 공유하고 저를 바로잡아 주시기 바랍니다:

package com.wangpeng.utill;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.PrintWriter;

/**
 * @author wangpeng
 * 
 */
public class ToolOfFile {

 /**
 * 创建目录
 * 
 * @param folderPath
 *      目录目录
 * @throws Exception
 */
 public static void newFolder(String folderPath) throws Exception {
 try {
  java.io.File myFolder = new java.io.File(folderPath);
  if (!myFolder.exists()) {
  myFolder.mkdir();
  }
 } catch (Exception e) {
  throw e;
 }
 }

 /**
 * 创建文件
 * 
 * @param filePath
 *      文件路径
 * @throws Exception
 */
 public static void newFile(String filePath) throws Exception {
 try {
  File myFile = new File(filePath);
  if (!myFile.exists()) {
  myFile.createNewFile();
  }
 } catch (Exception e) {
  throw e;
 }
 }

 /**
 * 创建文件,并写入内容
 * 
 * @param filePath
 *      文件路径
 * @param fileContent
 *      被写入的文件内容
 * @throws Exception
 */
 public static void newFile(String filePath, String fileContent)
  throws Exception {
 // 用来写入字符文件的便捷类
 FileWriter fileWriter = null;
 // 向文本输出流打印对象的格式化表示形式,使用指定文件创建不具有自己主动行刷新的新
 PrintWriter printWriter = null;
 try {
  File myFile = new File(filePath);
  if (!myFile.exists()) {
  myFile.createNewFile();
  }

  fileWriter = new FileWriter(myFile);
  printWriter = new PrintWriter(fileWriter);

  printWriter.print(fileContent);
  printWriter.flush();
 } catch (Exception e) {
  throw e;
 } finally {
  if (printWriter != null) {
  printWriter.close();
  }
  if (fileWriter != null) {
  fileWriter.close();
  }
 }
 }

 /**
 * 复制文件
 * 
 * @param oldPath
 *      被拷贝的文件
 * @param newPath
 *      复制到的文件
 * @throws Exception
 */
 public static void copyFile(String oldPath, String newPath)
  throws Exception {
 InputStream inStream = null;
 FileOutputStream outStream = null;
 try {
  int byteread = 0;
  File oldfile = new File(oldPath);
  // 文件存在时
  if (oldfile.exists()) {
  inStream = new FileInputStream(oldfile);
  outStream = new FileOutputStream(newPath);

  byte[] buffer = new byte[1444];
  while ((byteread = inStream.read(buffer)) != -1) {
   outStream.write(buffer, 0, byteread);
  }
  outStream.flush();
  }
 } catch (Exception e) {
  throw e;
 } finally {
  if (outStream != null) {
  outStream.close();
  }
  if (inStream != null) {
  inStream.close();
  }
 }
 }

 /**
 * 复制文件
 * @param inStream 被拷贝的文件的输入流
 * @param newPath 被复制到的目标
 * @throws Exception
 */
 public static void copyFile(InputStream inStream, String newPath)
  throws Exception {
 FileOutputStream outStream = null;
 try {
  int byteread = 0;
  outStream = new FileOutputStream(newPath);
  byte[] buffer = new byte[1444];
  while ((byteread = inStream.read(buffer)) != -1) {
  outStream.write(buffer, 0, byteread);
  }
  outStream.flush();
 } catch (Exception e) {
  throw e;
 } finally {
  if (outStream != null) {
  outStream.close();
  }
  if (inStream != null) {
  inStream.close();
  }
 }
 }

 /**
 * 复制目录
 * 
 * @param oldPath
 *      被复制的目录路径
 * @param newPath
 *      被复制到的目录路径
 * @throws Exception
 */
 public static void copyFolder(String oldPath, String newPath)
  throws Exception {
 try {
  (new File(newPath)).mkdirs(); // 假设目录不存在 则建立新目录
  File a = new File(oldPath);
  String[] file = a.list();
  File tempIn = null;
  for (int i = 0; i < file.length; i++) {
  if (oldPath.endsWith(File.separator)) {
   tempIn = new File(oldPath + file[i]);
  } else {
   tempIn = new File(oldPath + File.separator + file[i]);
  }

  if (tempIn.isFile()) {
   copyFile(tempIn.getAbsolutePath(),
    newPath + "/" + (tempIn.getName()).toString());
  } else if (tempIn.isDirectory()) {// 假设是子目录
   copyFolder(oldPath + "/" + file[i], newPath + "/" + file[i]);
  }
  }
 } catch (Exception e) {
  throw e;
 }
 }

 /**
 * 删除文件
 * 
 * @param filePathAndName
 */
 public static void delFileX(String filePathAndName) {
 File myDelFile = new File(filePathAndName);
 myDelFile.delete();
 }

 /**
 * 删除目录
 * 
 * @param path
 */
 public static void delForder(String path) {
 File delDir = new File(path);
 if (!delDir.exists()) {
  return;
 }
 if (!delDir.isDirectory()) {
  return;
 }
 String[] tempList = delDir.list();
 File temp = null;
 for (int i = 0; i < tempList.length; i++) {
  if (path.endsWith(File.separator)) {
  temp = new File(path + tempList[i]);
  } else {
  temp = new File(path + File.separator + tempList[i]);
  }

  if (temp.isFile()) {
  temp.delete();
  } else if (temp.isDirectory()) {
  // 删除完里面全部内容
  delForder(path + "/" + tempList[i]);
  }
 }
 delDir.delete();
 }

 public static void main(String[] args) {
 String oldPath = "F:/test/aaa/";
 String newPath = "F:/test/bbb/";

 try {
  // ToolOfFile.newFolder("F:/test/hello/");
  // ToolOfFile.newFile("F:/test/hello/world.txt","我爱你,the world!
");
  ToolOfFile.copyFolder(oldPath, newPath);
  // ToolOfFile.delForder("F:/test/hello");
 } catch (Exception e) {
  e.printStackTrace();
 }
 System.out.println("OK");
 }
}
로그인 후 복사

위 내용은 자바 파일 및 디렉토리의 추가, 삭제, 복사에 대한 자세한 설명의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

자바의 제곱근 자바의 제곱근 Aug 30, 2024 pm 04:26 PM

자바의 제곱근 안내 여기서는 예제와 코드 구현을 통해 Java에서 Square Root가 어떻게 작동하는지 설명합니다.

자바의 완전수 자바의 완전수 Aug 30, 2024 pm 04:28 PM

Java의 완전수 가이드. 여기서는 정의, Java에서 완전 숫자를 확인하는 방법, 코드 구현 예제에 대해 논의합니다.

Java의 난수 생성기 Java의 난수 생성기 Aug 30, 2024 pm 04:27 PM

Java의 난수 생성기 안내. 여기서는 예제를 통해 Java의 함수와 예제를 통해 두 가지 다른 생성기에 대해 설명합니다.

자바의 웨카 자바의 웨카 Aug 30, 2024 pm 04:28 PM

Java의 Weka 가이드. 여기에서는 소개, weka java 사용 방법, 플랫폼 유형 및 장점을 예제와 함께 설명합니다.

자바의 암스트롱 번호 자바의 암스트롱 번호 Aug 30, 2024 pm 04:26 PM

자바의 암스트롱 번호 안내 여기에서는 일부 코드와 함께 Java의 Armstrong 번호에 대한 소개를 논의합니다.

Java의 스미스 번호 Java의 스미스 번호 Aug 30, 2024 pm 04:28 PM

Java의 Smith Number 가이드. 여기서는 정의, Java에서 스미스 번호를 확인하는 방법에 대해 논의합니다. 코드 구현의 예.

Java Spring 인터뷰 질문 Java Spring 인터뷰 질문 Aug 30, 2024 pm 04:29 PM

이 기사에서는 가장 많이 묻는 Java Spring 면접 질문과 자세한 답변을 보관했습니다. 그래야 면접에 합격할 수 있습니다.

Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Java 8 Stream foreach에서 나누거나 돌아 오시겠습니까? Feb 07, 2025 pm 12:09 PM

Java 8은 스트림 API를 소개하여 데이터 컬렉션을 처리하는 강력하고 표현적인 방법을 제공합니다. 그러나 스트림을 사용할 때 일반적인 질문은 다음과 같은 것입니다. 기존 루프는 조기 중단 또는 반환을 허용하지만 스트림의 Foreach 메소드는이 방법을 직접 지원하지 않습니다. 이 기사는 이유를 설명하고 스트림 처리 시스템에서 조기 종료를 구현하기위한 대체 방법을 탐색합니다. 추가 읽기 : Java Stream API 개선 스트림 foreach를 이해하십시오 Foreach 메소드는 스트림의 각 요소에서 하나의 작업을 수행하는 터미널 작동입니다. 디자인 의도입니다

See all articles