怎样用JAVA编写把一个文件夹中的文件复制到一个指定的文件夹用完文件后再把它还原到原文件夹 java中如何实现将指定路径下的文件复制到另一路径下

\u7528Java\u7f16\u5199\u4e00\u4e2a\u7a0b\u5e8f\uff0c\u5c06\u4e00\u4e2a\u56fe\u50cf\u6587\u4ef6\u590d\u5236\u5230\u6307\u5b9a\u7684\u6587\u4ef6\u5939\u4e2d

\u8fd9\u662f\u6211\u4eec\u516c\u53f8\u57fa\u7c7b\u91cc\u7684\u4e00\u4e2a\u65b9\u6cd5\u5e0c\u671b\u5bf9\u4f60\u6709\u5e2e\u52a9\u3002\u3002/**
* \u590d\u5236\u5355\u4e2a\u6587\u4ef6
* @param oldPath String \u539f\u6587\u4ef6\u8def\u5f84 \u5982\uff1ac:/fqf.txt
* @param newPath String \u590d\u5236\u540e\u8def\u5f84 \u5982\uff1af:/fqf.txt
* @return boolean
*/
public void copyFile(String oldPath, String newPath) {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPath);
if (oldfile.exists()) { //\u6587\u4ef6\u5b58\u5728\u65f6
InputStream inStream = new FileInputStream(oldPath); //\u8bfb\u5165\u539f\u6587\u4ef6
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //\u5b57\u8282\u6570 \u6587\u4ef6\u5927\u5c0f
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("\u590d\u5236\u5355\u4e2a\u6587\u4ef6\u64cd\u4f5c\u51fa\u9519");
e.printStackTrace(); } }

renameTo(File dest) \u65b9\u6cd5 \u7684\u4f5c\u7528\u662f\uff0c\u91cd\u65b0\u547d\u540d\u6b64\u62bd\u8c61\u8def\u5f84\u540d\u8868\u793a\u7684\u6587\u4ef6
\u4f60\u7528\u8fd9\u4e2a\u53ea\u662f\u5c06\u8be5\u6587\u4ef6\u6362\u4e86\u4e00\u4e2a\u8def\u5f84\uff0c\u4e5f\u5c31\u662f\u6362\u4e86\u4e00\u4e2a\u4f4d\u7f6e\u800c\u5df2\uff0c\u5e76\u4e0d\u662f\u590d\u5236\u3002
\u4f60\u8981\u590d\u5236\u7684\u8bdd\uff0c\u8c8c\u4f3c\u53ea\u80fd\u65b0\u5efa\u4e00\u4e2a\u6587\u4ef6\uff0c\u8be5\u6587\u4ef6\u7684\u8def\u5f84\u662f\u5c06\u539f\u6587\u4ef6\u590d\u5236\u5230\u7684\u8def\u5f84\uff1b\u7136\u540e\u5c06\u65e7\u6587\u4ef6\u7684\u5185\u5bb9\u8bfb\u51fa\u6765\uff0c\u5199\u5165\u5230\u65b0\u6587\u4ef6\u4e2d\u53bb\uff0c\u8fd9\u6837\u5c31\u5b9e\u73b0\u4e86\u6587\u4ef6\u7684\u590d\u5236

给你个文件操作的工具类,自己研究一下吧,呵呵
package com.mobileSky.ty.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.util.StringTokenizer;

public class FileUtil {

/**
* 读取文本文件内容
*
* @param filePathAndName
* 带有完整绝对路径的文件名
* @param encoding
* 文本文件打开的编码方式
* @return 返回文本文件的内容
*/
public static String readTxt(String filePathAndName, String encoding)
throws IOException {
encoding = encoding.trim();
StringBuffer str = new StringBuffer("");
String st = "";
try {
FileInputStream fs = new FileInputStream(filePathAndName);
InputStreamReader isr;
if (encoding.equals("")) {
isr = new InputStreamReader(fs);
} else {
isr = new InputStreamReader(fs, encoding);
}
BufferedReader br = new BufferedReader(isr);
try {
String data = "";
while ((data = br.readLine()) != null) {
str.append(data + "\r\n");
}
} catch (IOException e) {
str.append(e.toString());
}
st = str.toString();
} catch (IOException es) {
throw es;
}
return st;
}

/**
* 新建文件
*
* @param filePathAndName
* 文本文件完整绝对路径及文件名
* @param fileContent
* 文本文件内容
* @return
* @throws Exception
*/
public static void createFile(String filePathAndName, String fileContent)
throws Exception {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
FileWriter resultFile = new FileWriter(myFilePath);
PrintWriter myFile = new PrintWriter(resultFile);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
resultFile.close();
} catch (Exception e) {
throw new Exception("创建文件操作出错", e);
}
}

/**
* 有编码方式的文件创建
*
* @param filePathAndName
* 文本文件完整绝对路径及文件名
* @param fileContent
* 文本文件内容
* @param encoding
* 编码方式 例如 GBK 或者 UTF-8
* @return
* @throws Exception
*/
public static void createFile(String filePathAndName, String fileContent,
String encoding) throws Exception {

try {
String filePath = filePathAndName;
filePath = filePath.toString();
File myFilePath = new File(filePath);
if (!myFilePath.exists()) {
myFilePath.createNewFile();
}
PrintWriter myFile = new PrintWriter(myFilePath, encoding);
String strContent = fileContent;
myFile.println(strContent);
myFile.close();
} catch (Exception e) {
throw new Exception("创建文件操作出错", e);
}
}

/**
* 创建文件夹
*
* @param filePath
* @throws Exception
*/
public static String createFolder(String filePath) throws Exception {
File file = new java.io.File(filePath);
try {
if (!file.exists()) {
if (!file.mkdir()) {
throw new IOException("创建文件夹:" + filePath + "出错");
}
}
return filePath;
} catch (Exception e) {
throw e;
}
}

/**
* 多级目录创建
*
* @param folderPath
* 准备要在本级目录下创建新目录的目录路径 例如 E:\\Test\\java\\
* @param paths
* 无限级目录参数,各级目录以单数线区分 例如 a|b|c
* @return 返回创建文件夹后的路径 例如 c:myfa c
* @throws Exception
*/
public static String createFolders(String folderPath, String paths)
throws Exception {
String txts = folderPath;
try {
String txt;
txts = folderPath;
StringTokenizer st = new StringTokenizer(paths, "|");
for (int i = 0; st.hasMoreTokens(); i++) {
txt = st.nextToken().trim();
txts = createFolder(txts + txt + "/");
}
} catch (Exception e) {
throw new Exception("创建目录操作出错!", e);
}
return txts;
}

/**
* 复制单个文件
*
* @param oldPathFile
* 准备复制的文件源
* @param newPathFile
* 拷贝到新绝对路径带文件名
* @return
* @throws Exception
*/
public static void copyFile(String oldPathFile, String newPathFile)
throws Exception {
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldPathFile);
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldPathFile); // 读入原文件
FileOutputStream fs = new FileOutputStream(newPathFile);
byte[] buffer = new byte[1444];
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
throw e;
}
}

/**
* <p>
* 将sourceFolder文件夹下的内容复制到destinationFolder文件夹下
* </p>
* <p>
* 如destinationFolder文件夹不存在则自动创建
* </p>
*
* @param sourceFolder
* 源文件夹 如:C:\\aaa
* @param destinationFolder
* 目标文件夹 D:\\java
* @throws Exception
*/
public static void copyFolder(String sourceFolder, String destinationFolder)
throws Exception {
try {
new File(destinationFolder).mkdirs(); // 如果文件夹不存在 则建立新文件夹
File a = new File(sourceFolder);
String[] file = a.list();
File temp = null;
for (int i = 0; i < file.length; i++) {
if (sourceFolder.endsWith(File.separator)) {
temp = new File(sourceFolder + file[i]);
} else {
temp = new File(sourceFolder + File.separator + file[i]);
}
if (temp.isFile()) {
FileInputStream input = new FileInputStream(temp);
FileOutputStream output = new FileOutputStream(
destinationFolder + "/"
+ (temp.getName()).toString());
byte[] b = new byte[1024 * 5];
int len;
while ((len = input.read(b)) != -1) {
output.write(b, 0, len);
}
output.flush();
output.close();
input.close();
}
if (temp.isDirectory()) {// 如果是子文件夹
copyFolder(sourceFolder + "/" + file[i], destinationFolder
+ "/" + file[i]);
}
}
} catch (Exception e) {
throw new Exception("复制整个文件夹内容操作出错", e);
}
}

/**
* 删除文件
*
* @param filePathAndName
* 文本文件完整绝对路径及文件名
* @return Boolean 成功删除返回true遭遇异常返回false
*/
public static void delFile(String filePathAndName) throws Exception {
try {
String filePath = filePathAndName;
File myDelFile = new File(filePath);
if (myDelFile.exists()) {
myDelFile.delete();
} else {
throw new IOException(filePathAndName + "删除文件操作出错");
}
} catch (IOException e) {
throw new Exception(filePathAndName + "删除文件操作出错", e);
}
}

/**
* 删除文件夹
*
* @param folderPath
* 文件夹完整绝对路径
* @return
* @throws Exception
*/
public static void delFolder(String folderPath) throws Exception {

try {
delAllFile(folderPath);
// 删除完里面所有内容
String filePath = folderPath;
filePath = filePath.toString();
java.io.File myFilePath = new java.io.File(filePath);
boolean result = myFilePath.delete(); // 删除空文件夹
if (!result) {
throw new IOException("文件夹:" + folderPath + ",删除失败");
}
} catch (IOException e) {
throw new Exception("删除文件夹出错", e);
}
}

/**
* 删除文件及文件夹下所有文件
*
* @return
* @throws IOException
*/
public static boolean delAllFile(String filePath) throws IOException {
File file = new File(filePath);
if (!file.exists())// 文件夹不存在不存在
throw new IOException("指定目录不存在:" + file.getName());
boolean rslt = true;// 保存中间结果
if (!(rslt = file.delete())) {// 先尝试直接删除
// 若文件夹非空。枚举、递归删除里面内容
File subs[] = file.listFiles();
for (int i = 0; i <= subs.length - 1; i++) {
if (subs[i].isDirectory())
delAllFile(subs[i].toString());// 递归删除子文件夹内容
rslt = subs[i].delete();// 删除子文件夹本身
}
// rslt = file.delete();// 删除此文件夹本身
}

if (!rslt)
throw new IOException("无法删除:" + file.getName());
// 删除文件
return true;
}

/**
* 移动文件
*
* @param oldPath
* @param newPath
* @return
* @throws Exception
*/
public static void moveFile(String oldPath, String newPath)
throws Exception {

try {
copyFile(oldPath, newPath);
delFile(oldPath);
} catch (Exception e) {
throw e;
}

}

/**
* 移动目录
*
* @param oldPath
* @param newPath
* @return
*/
public static void moveFolder(String oldPath, String newPath) {
try {
copyFolder(oldPath, newPath);
delFolder(oldPath);
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}
}

/**
* <p>
* 取得当前类文件所在绝对路径
* </p>
* <p>
* 如:E:/workspace/mobile/WebRoot/WEB-INF/classes/com/mobileSky/ty/utils/
* </p>
*
* @return
*/
public static String getClassPath() {
String strClassName = FileUtil.class.getName();

String strPackageName = "";
if (FileUtil.class.getPackage() != null) {
strPackageName = FileUtil.class.getPackage().getName();
}

String strClassFileName = "";
if (!"".equals(strPackageName)) {
strClassFileName = strClassName.substring(
strPackageName.length() + 1, strClassName.length());
} else {
strClassFileName = strClassName;
}

URL url = null;
url = FileUtil.class.getResource(strClassFileName + ".class");
String strURL = url.toString();
strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
.lastIndexOf('/'));
return strURL + "/";
}

/**
* 取得当前项目根目录,如:E:/workspace/mobile/,其中mobile为项目名
*
* @param projectName
* @return
*/
public static String getProject(String projectName) {
String classPath = getClassPath();
return classPath.substring(0, classPath.indexOf(projectName)
+ projectName.length() + 1);
}

/**
* 将C:\aaa\dsa转换为C:/aaa/dsa
*
* @param path
* @return
*/
public static String getStr(String path) {
String result = "";
char[] pathChar = path.toCharArray();
for (int i = 0; i < pathChar.length; i++) {
if (pathChar[i] == '\\') {
pathChar[i] = '/';
}
result += pathChar[i];
}
return result;
}

public static void main(String arg[]) {

try {
// copyFolder("C:\\aaa", "E:\\Test\\java");
// delAllFile("E:\\Test\\java");
// delFolder("E:\\Test\\java");
// createFile("E:\\Test\\java\\a.xml",
// "<abc>\r\n<a>\r\n</a>\r\n</abc>");
// createFolder("E:\\Test\\java");
// createFolders("E:\\Test\\java\\", "一级|二级|三级");
String a = readTxt("E:\\Test\\java\\a.xml", "GBK");
System.out.println(a);
} catch (IOException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
} catch (Exception e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}

}
}

不难,随便找本Java语法书看看IO那章就Ok了.导师?莫非是研究生,这点那更不在话下.

我的这个是复制个.exe的安装程序:(源代码)

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

public class CopyJDK {
public static void main(String[] args) {
/*指定源exe文件的存放路径*/
String str = "f:/jdk-1_5_0_06-windows-i586-p.exe";
/*指定复制后的exe的目标路径*/
String strs = "e:/copy.exe";
/*创建输入和输出流*/
FileInputStream fis = null;
FileOutputStream fos = null;

try {
/*将io流和文件关联*/
fis = new FileInputStream(str);

fos = new FileOutputStream(strs);
byte[] buf = new byte[1024*1024];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);

}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

public class CopyFile {
public static void main(String[] args) throws IOException {
FileInputStream readFis=new FileInputStream("d:/1.txt");
FileChannel readFc=readFis.getChannel();
ByteBuffer bb=ByteBuffer.allocate(1024);
readFc.read(bb);
FileOutputStream writeFis=new FileOutputStream("d:/2.txt");
FileChannel writeFs=writeFis.getChannel();
writeFs.write((ByteBuffer) bb.flip());

}
}

你多看下j2se的输入输出流那章啊,自己看API,无非就用输入输出流那几个封装好的类的方法倒来倒去。。 学习不能浮躁。。

  • java濡備綍鍒涘缓鏂囦欢澶
    绛旓細1. 浣跨敤`mkdir`鏂规硶锛歚File`绫讳腑鐨刞mkdir`鏂规硶鐢ㄤ簬鍒涘缓鍗曚釜鐩綍銆傚鏋滅埗鐩綍宸茬粡瀛樺湪骞朵笖鍏锋湁鐩稿簲鐨勬潈闄愶紝姝ゆ柟娉曞皢鎴愬姛鍒涘缓鐩綍銆備絾濡傛灉鐖剁洰褰曚笉瀛樺湪锛岃鏂规硶灏嗕笉浼氬垱寤轰换浣曠洰褰曘傜ず渚嬩唬鐮侊細java File dir = new File; // 鍒涘缓File瀵硅薄锛屾寚瀹氳鍒涘缓鐨勬枃浠跺す璺緞 if) { // 浣跨敤mkdir鏂规硶鍒涘缓鏂囦欢澶 ...
  • 鎬庢牱鐢╦ava鍦ㄦ寚瀹氳矾寰勪笅鍒涘缓涓涓枃浠跺す
    绛旓細// String directory = "myDir1/myDir2";String fileName = "myFile.txt";// 鍦ㄥ唴瀛樹腑鍒涘缓涓涓枃浠瀵硅薄锛屾敞鎰忥細姝ゆ椂杩樻病鏈夊湪纭洏瀵瑰簲鐩綍涓嬪垱寤哄疄瀹炲湪鍦ㄧ殑鏂囦欢 File f = new File(directory,fileName);if(f.exists()) { // 鏂囦欢宸茬粡瀛樺湪锛岃緭鍑烘枃浠剁殑鐩稿叧淇℃伅 System.out.println(f.getAbs...
  • 濡備綍鐢↗AVA浠g爜鍒涘缓涓涓枃浠跺す?
    绛旓細File绫婚噷闈㈡湁涓や釜鏂规硶鍙互瀹炵幇锛歕x0d\x0a涓涓鏄痬kdir():鍒涘缓姝ゆ娊璞¤矾寰勫悕鎸囧畾鐨勭洰褰曘俓x0d\x0a鍙﹀涓涓槸mkdirs(): 鍒涘缓姝ゆ娊璞¤矾寰勫悕鎸囧畾鐨勭洰褰曪紝鍖呮嫭鎵鏈夊繀闇浣嗕笉瀛樺湪鐨勭埗鐩綍銆俓x0d\x0a\x0d\x0a姣斿浣犳兂鍦ˋ鏂囦欢澶鍒涘缓涓涓狟鏂囦欢澶癸紝骞跺湪B鏂囦欢澶逛笅鍒涘缓c鍜孌鏂囦欢澶癸紝鍙互鐢ㄤ笅闈㈢殑浠g爜...
  • 鐢╦ava缂栫▼鏂板缓涓涓枃浠跺す,鐒跺悗寰鏂囦欢澶归噷鍐欏叆txt鏂囨。
    绛旓細java.io.File file = new java.io.File(folder, "test1.txt");java.io.FileOutputStream fou=new java.io.FileOutputStream(file);fou.write("Test line 1\r\n");fou.write("Test line 2\r\n");fou.close();澶т綋濡傛锛岃鍙傝
  • java 鎬庝箞鐢File寤鏂囦欢鈥滃す鈥
    绛旓細import java.io.File;public class CreateDirectory { public static void main(String[] args) { //寤虹珛涓涓枃浠跺す File file=new File("E:\\workspace");if(!file.exists()){//濡傛灉涓嶅瓨鍦ㄨ鏂囦欢澶 file.mkdir();//鏂板缓 } //寤虹珛澶氫釜鏂囦欢澶 File file1=new File("E:\\work\\test\\...
  • java 缂栧啓绋嬪簭,鎷疯礉涓涓甯﹀唴瀹圭殑鏂囦欢澶銆 渚嬪:灏c:\program files\java...
    绛旓細涓銆佸鍒鏂囦欢浠g爜 print?import java.io.*;import java.util.*;class Copy { static void copy(String from,String to) throws IOException { BufferedReader in=new BufferedReader(new FileReader(from));BufferedWriter out=new BufferedWriter(new FileWriter(new File(to)));String line=null;while(...
  • java濡備綍鎷疯礉涓涓枃浠跺す鍐呯殑澶氫釜鎸囧畾鐨勬枃浠跺埌鍙﹀涓涓寚瀹氱殑鏂囦欢澶逛笅...
    绛旓細璇风湅浠g爜锛/*** 鎶婁竴涓枃浠跺す閲岀殑鎵鏈夋枃浠跺寘鎷枃浠跺す 涓骞跺師鏍锋嫹璐濆埌鍙︿竴涓洰褰曚腑锛*@author shuishui*/ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java...
  • 鎬庢牱鐢↗AVA缂栧啓鎶婁竴涓枃浠跺す涓殑鏂囦欢澶嶅埗鍒颁竴涓寚瀹氱殑鏂囦欢澶圭敤瀹屾枃浠跺悗...
    绛旓細* 灏唖ourceFolder鏂囦欢澶涓嬬殑鍐呭澶嶅埗鍒癲estinationFolder鏂囦欢澶逛笅 * * * 濡俤estinationFolder鏂囦欢澶逛笉瀛樺湪鍒欒嚜鍔ㄥ垱寤 * * * @param sourceFolder * 婧愭枃浠跺す 濡:C:\\aaa * @param destinationFolder * 鐩爣鏂囦欢澶 D:\\java * @throws Exception */ public static void copyFolder(String sourceFolder,...
  • Java缂栧啓浠g爜,鍦―鐩樹笅鍒涘缓abc鏂囦欢澶,鐒跺悗鍦╝bc鏂囦欢澶逛腑鍒涘缓abc鏂囦欢,姹...
    绛旓細Java浠g爜锛歩mport java.io.File;import java.io.IOException;public class Test10 { public static void main(String[] args) { //鍒涘缓鈥渁bc鈥鏂囦欢澶 String pathName = "d:\\abc";File path = new File(pathName);path.mkdir();//鍒涘缓鈥渁bc鈥濇枃浠 String fileName = "d:\\abc\\abc";File...
  • java 鍦ㄦ寚瀹氱殑鏂囦欢澶涓嬪垱寤涓涓鏂扮殑鏂囦欢澶
    绛旓細鍙互鍏堝垏鎹㈠埌鎸囧畾鐨鏂囦欢澶璺緞涓嬶紝涔嬪悗鐩存帴閫氳繃mkdir鏂规硶杩涜鏂囦欢澶瑰垱寤恒備妇渚嬶細String path = "d:/oldfilepath";//瀹氫箟鎸囧畾鏂囦欢璺緞 String newPath = path+"/newpath";//鎸囧畾鏂拌矾寰 File file = new File(newPath );//瀹氫箟涓涓枃浠娴 file.mkdir();//鍒涘缓鏂囦欢澶 澶囨敞锛氬鏋滀笉纭畾鍘熸湁鏂囦欢澶...
  • 扩展阅读:学java一般能干什么 ... java如何打开一个文件 ... java如何导入一个文件 ... java编程常用软件 ... java怎么导入一个文件 ... java中怎么创建文件 ... 如何用java创建源文件 ... java用什么软件编写 ... java中怎样编写一个方法 ...

    本站交流只代表网友个人观点,与本站立场无关
    欢迎反馈与建议,请联系电邮
    2024© 车视网