検索
ホームページJava&#&チュートリアル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");
 }
}

以上がJavaでのファイルやディレクトリの追加・削除・コピーについて詳しく解説の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
JVMはオペレーティングシステムAPIの違いをどのように処理しますか?JVMはオペレーティングシステムAPIの違いをどのように処理しますか?Apr 27, 2025 am 12:18 AM

JVMは、JavanativeInterface(JNI)およびJava Standard Libraryを介してオペレーティングシステムのAPIの違いを処理します。1。JNIでは、Javaコードがローカルコードを呼び出し、オペレーティングシステムAPIと直接対話できます。 2. Java Standard Libraryは統一されたAPIを提供します。これは、異なるオペレーティングシステムAPIに内部的にマッピングされ、コードがプラットフォーム間で実行されるようにします。

Java 9で導入されたモジュール性は、プラットフォームの独立性にどのように影響しますか?Java 9で導入されたモジュール性は、プラットフォームの独立性にどのように影響しますか?Apr 27, 2025 am 12:15 AM

modularitydoesnotdirectlyectlyectjava'splatformindepensence.java'splatformendepenceismaindainededainededainededaindainedaindained bythejvm、butmodularityinfluencesApplucationStructure andmanagement、間接的なインパクチャプラット形成依存性.1)

ByteCodeとは何ですか?また、Javaのプラットフォームの独立性とどのように関係していますか?ByteCodeとは何ですか?また、Javaのプラットフォームの独立性とどのように関係していますか?Apr 27, 2025 am 12:06 AM

bytecodeinjavaisthe intermediaterepresentationthateNablesplatformindepence.1)javacodeis compiledintobytecodestoredin.classfiles.2)thejvminterpretsorcompilesthisbytecodeintomachinecodeatime、

Javaがプラットフォームに依存しない言語と見なされるのはなぜですか?Javaがプラットフォームに依存しない言語と見なされるのはなぜですか?Apr 27, 2025 am 12:03 AM

javaachievesplatformedenceTheTheTheJavavirtualMachine(JVM)、これは、javacodeisisisisisissompiledIntobytecode.2)javaCodeisisisisissompiledevedevicetecode.2)

グラフィカルユーザーインターフェイス(GUI)は、Javaのプラットフォーム独立性の課題をどのように提示できますか?グラフィカルユーザーインターフェイス(GUI)は、Javaのプラットフォーム独立性の課題をどのように提示できますか?Apr 27, 2025 am 12:02 AM

Javagui開発におけるプラットフォームの独立性は課題に直面していますが、Swing、Javafx、統一外観、パフォーマンス最適化、サードパーティライブラリ、クロスプラットフォームテストを使用することで対処できます。 Javaguiの開発は、クロスプラットフォームの一貫性を提供することを目的としたAWTとSwingに依存していますが、実際の効果はオペレーティングシステムごとに異なります。ソリューションには以下が含まれます。1)SwingおよびJavafxをGUIツールキットとして使用します。 2)uimanager.setlookandfeel()を介して外観を統合します。 3)さまざまなプラットフォームに合わせてパフォーマンスを最適化します。 4)ApachepivotやSWTなどのサードパーティライブラリを使用する。 5)一貫性を確保するために、クロスプラットフォームテストを実施します。

Java開発のどの側面がプラットフォームに依存していますか?Java開発のどの側面がプラットフォームに依存していますか?Apr 26, 2025 am 12:19 AM

javadevelopmentisnotentirelylylypratform-IndopentDuetoseveralfactors.1)jvmvariationsaffectperformanceandbehavioracrossdifferentos.2)nativeLibrariesviajniintroducePlatform-specificissues.3)giaiasystemsdifferbeTioneplateplatifflics.4)

さまざまなプラットフォームでJavaコードを実行するときにパフォーマンスの違いはありますか?なぜ?さまざまなプラットフォームでJavaコードを実行するときにパフォーマンスの違いはありますか?なぜ?Apr 26, 2025 am 12:15 AM

Javaコードは、さまざまなプラットフォームで実行するときにパフォーマンスの違いがあります。 1)JVMの実装と最適化戦略は、OracleJDKやOpenJDKなどとは異なります。 2)メモリ管理やスレッドスケジューリングなどのオペレーティングシステムの特性もパフォーマンスに影響します。 3)適切なJVMを選択し、JVMパラメーターとコード最適化を調整することにより、パフォーマンスを改善できます。

Javaのプラットフォームの独立性の制限は何ですか?Javaのプラットフォームの独立性の制限は何ですか?Apr 26, 2025 am 12:10 AM

java'splatformindepentedencehaslimitationsincludingporformanceoverhead、versioncompatibulisisues、changleSwithnativeLibraryIntegration、プラットフォーム固有の機能、およびjvminStallation/maintenation。

See all articles

ホット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衣類リムーバー

Video Face Swap

Video Face Swap

完全無料の AI 顔交換ツールを使用して、あらゆるビデオの顔を簡単に交換できます。

ホットツール

AtomエディタMac版ダウンロード

AtomエディタMac版ダウンロード

最も人気のあるオープンソースエディター

ドリームウィーバー CS6

ドリームウィーバー CS6

ビジュアル Web 開発ツール

EditPlus 中国語クラック版

EditPlus 中国語クラック版

サイズが小さく、構文の強調表示、コード プロンプト機能はサポートされていません

Dreamweaver Mac版

Dreamweaver Mac版

ビジュアル Web 開発ツール

SublimeText3 英語版

SublimeText3 英語版

推奨: Win バージョン、コードプロンプトをサポート!