怎样用JAVA编写把一个文件夹中的文件复制到一个指定的文件夹用完文件后再把它还原到原文件夹

用Java编写一个程序,将一个图像文件复制到指定的文件夹中~

这是我们公司基类里的一个方法希望对你有帮助。。/**
* 复制单个文件
* @param oldPath String 原文件路径 如:c:/fqf.txt
* @param newPath String 复制后路径 如:f:/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()) { //文件存在时
InputStream inStream = new FileInputStream(oldPath); //读入原文件
FileOutputStream fs = new FileOutputStream(newPath);
byte[] buffer = new byte[1444];
int length;
while ( (byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; //字节数 文件大小
// System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
}
catch (Exception e) {
System.out.println("复制单个文件操作出错");
e.printStackTrace(); } }

renameTo(File dest) 方法 的作用是,重新命名此抽象路径名表示的文件
你用这个只是将该文件换了一个路径,也就是换了一个位置而已,并不是复制。
你要复制的话,貌似只能新建一个文件,该文件的路径是将原文件复制到的路径;然后将旧文件的内容读出来,写入到新文件中去,这样就实现了文件的复制

给你个文件操作的工具类,自己研究一下吧,呵呵
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语言编写程序,把一个已存在的txt文件读出来并写进另一个txt文件...
答:import java.io.BufferedReader;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;public class CopyDemo {public static void main(String[] args) throws Exception {/...

用JAVA编程完成一下文件的建立和复制?
答://自己选择复制的文件和选择复制的路径 import java.awt.Container;import java.awt.FlowLayout;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.io.*;import javax.swing.*;public class...

java实现:将一个记事本文件内容复制到另一个文件
答:import java.io.InputStreamReader;/** * java读写文件,复制文件 * 读取d:/1.txt文件内容,写入f:/text.txt文件中. * @author young * */public class FileWriterTest {// 读写文件public static void rwFile(){Fi...

怎样用java程序实现文件拷贝
答:6.将步骤二中的判断并拷贝文件的代码写在一个main函数中,执行拷贝,拷贝完成。结果拷贝大小和源文件大小一致,成功。7.在执行前,记得输入参数。如果是使用命令提示符,执行 javac CopyFile.java 之后,执行 java CopyFile ...

编写一个java程序,将file1.txt文件中的内容复制到file2.txt中_百度...
答:public static void main(String[] args) throws Exception{ FileReader fr = null;FileWriter fw = null;int b = 0;char[] cbuf = new char[18];fr = new FileReader("E:\\java\\io\\1.txt");//1.txt保存...

java怎么把文本内容在指定文件夹里
答:java写入文件到指定文件夹的方法主要有两种:利用PrintStream和利用StringBuffer 例如将文本“I'm the text to be write”写入到文件夹D:/test下,并命名为test.txt,则两种方式简单实现代码如下:1. 利用PrintStream写文件 ...

用JAVA语言编写程序:文件一的内容复制到文件二,并且复制过去后小写变成...
答:import java.io.IOException;public class Test1 { public static void main(String[] args) throws IOException { String filename="d:\\1.txt";BufferedReader br = new BufferedReader(new FileReader(new File(filename...

java编程:编写一个文件信息存储程序,用户通过键盘输入学生的姓名,性 ...
答://test.java import java.io.*;import java.util.*;public class test { public static void main (String[] args) { try{ String strName="";String strSex="";int i=1;//构造写入文件的File对象 File file2=...

Java如何实现读取一个txt文件的所有内容,然后提取所需的部分并把它写 ...
答:import java.io.OutputStreamWriter;import java.util.ArrayList;import java.util.List;public class App {/** * 保存 list 到指定文件 * @param list * @param filePath * @throws IOException * @throws FileNot...

java怎样向一个文件(如txt文件)中写入一段数据,能够保存,然后下一次打 ...
答:import java.io.Writer ;import java.io.FileWriter ;public class WriterDemo02{ public static void main(String args[]) throws Exception{// 异常抛出,不处理 // 第1步、使用File类找到一个文件 File f= new File...

IT评价网,数码产品家用电器电子设备等点评来自于网友使用感受交流,不对其内容作任何保证

联系反馈
Copyright© IT评价网