文件夹F:\\txt中有很多txt文件,用java随机读取一个txt文件,然后将之复制粘贴到D:\\txt中。

如题:文件夹F://txt中有很多txt文件,用java随机读取一个txt文件,然后将之复制粘贴到D://txt中。请问代码怎么写?给出可行代码即可给悬赏分,另外再给20分。条件是java代码。

import java.io.File;

public class FileTest {

public static void main(String[] args) {
File files = new File("F:\\txt\\");
File file[] = files.listFiles();//获得目录中的文件及子目录信息
int i = (int) (Math.random()*file.length);
fun(file,i);
}
public static void fun(File file[],int i){
if(file[i].exists()){//如果文件存在
String name = file[i].getName();//获取文件名
if(file[i].isFile()&&name.endsWith(".txt")){ //如果是文件并且后缀名为.txt
File dest = new File("D:\\txt\\"+file[i].getName());
file[i].renameTo(dest);
}
else{
int j = (int) (Math.random()*file.length);
fun(file,j);
}
}else{
int j = (int) (Math.random()*file.length);
fun(file,j);
}
}
}追问

我想问一下复制过来的文件可以进行一下重命名吗?

追答

可以的,File dest = new File("D:\\txt\\"+新文件名);

追问

可以只是复制,而不是剪切吗?

追答

加一个方法对文件进行读写操作。具体看代码

        // 实现文件复制
public static void copyFile(File file1, File file2) {
try {
int byteread = 0;
if (file1.exists()) {// 如果文件存在
InputStream instream = new FileInputStream(file1); // 负责文件的读取
FileOutputStream fos = new FileOutputStream(file2); // 负责文件的写入
byte[] buffer = new byte[1024];
while ((byteread = instream.read(buffer)) != -1) {
fos.write(buffer, 0, byteread);
}
instream.close();
}
} catch (Exception e) {
System.out.println("复制文件操作出错!");
e.printStackTrace();
}
}

 在上面的方法调用就行。具体就是把file[i].renameTo(dest);这句代码改成copyFile(file[i],dest);

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-07-21
public static void copyFile(String rootPath, String copyToPath) throws IOException {
File rootPathFile = new File(rootPath);
File copyToPathFile = new File(copyToPath);

if (!rootPathFile.exists()) {
System.err.println(rootPath + " 目录不存在");
return;
}

if (!copyToPathFile.exists()) {
boolean b = copyToPathFile.mkdirs();// 创建目录
if (!b) {
System.err.println(copyToPath + " 创建目录失败");
return;// 创建目录失败直接返回
}
}
File[] txtFiles = rootPathFile.listFiles(new FilenameFilter() {

@Override
public boolean accept(File dir, String name) {
if (name.toLowerCase().endsWith("txt")) {
// 筛选txt类型文件
return true;
}
return false;
}
});

if (txtFiles != null) {
Random r = new Random();
int i = r.nextInt(txtFiles.length);// 随机获取0到txtFiles.length之间的数字
File copyFile = txtFiles[i];
File newFile = new File(copyToPath + "\\" + copyFile.getName());
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(copyFile), "UTF-8"));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF-8"));
String tmp = null;
while (true) {
tmp = br.readLine();
if (tmp == null) {
break;
}
bw.write(tmp);
bw.write("\n");// 写入换行符
}
if (bw != null) {
bw.flush();
bw.close();
}
if (br != null) {
br.close();
}
System.out.println("操作执行完毕");
}

}

第2个回答  2013-07-11

代码给你贴下面,望采纳

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

public class FileUtil
{
    public static void main(String[] args)
    {
        String path1 = "F:/abc.txt";
        String path2 = "D:/abc.txt";
        fileUtil(path1, path2);
    }

    /**
     * 复制单个文件
     * 
     * @param oldPath
     *            String 原文件路径 如:F:/abc.txt
     * @param newPath
     *            String 复制后路径 如:D:/abc.txt
     * @return boolean
     */
    public static void fileUtil(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();

        }

    }

}

第3个回答  2013-07-11
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;

public class RandomFileDemo {

    public static void main(String[] args) {
        String oldPath = "D:/Program Files";
        String newPath = "E:";
        randomCopyFile(oldPath, newPath);
    }

    /**
     * 随机复制文件
     * @param oldPath
     * @param newPath
     */
    static void randomCopyFile(String oldPath, String newPath) {
        BufferedReader reader = null;
        BufferedWriter writer = null;
        try {
            File file = new File(oldPath);
            File[] files = file.listFiles();// 遍历文件夹
            ArrayList<String> list = new ArrayList<String>();// 存储txt文件名称
            for (int i = 0; i < files.length; i++) {// 遍历txt文件,将文件名称放入集合
                String fileName = files[i].getName();
                if (fileName.endsWith(".txt")) {
                    list.add(fileName);
                }
            }
            Random random = new Random();
            String fileName = list.get(random.nextInt(list.size()));// 取随机文件名称
            file = new File(oldPath + File.separator + fileName);// 打开文件
            reader = new BufferedReader(new FileReader(file));
            String line = "";
            StringBuffer sb = new StringBuffer();
            while ((line = reader.readLine()) != null) {// 生成新的文本字符串
                sb.append(line).append("\n");
            }
            String newFile = newPath + File.separator + fileName;// 新文件路径
            System.out.println("生成新文件路径:" + newFile);
            file = new File(newFile);// 打开文件
            if (!file.exists()) file.createNewFile();// 创建新文件
            writer = new BufferedWriter(new FileWriter(file));
            writer.write(sb.toString());// 写数据
            writer.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {// 关闭流
                if (reader != null) reader.close();
                if (writer != null) writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

第4个回答  2013-07-11
package com;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class FileOperator {

public static void main(String[] args) {

String pathD = "D:/txt";
String pathF = "F:/txt";

File directoryF = new File(pathF);
File[] filesF = directoryF.listFiles();

// 随机生成文件数组下标,用于随机选择一个文件
Random r = new Random();
int filesFCount = filesF.length;
int index = r.nextInt(filesFCount);
// 拷贝到D盘的文件
File copyedFile = new File(pathD +"/"+ filesF[index].getName());

// 利用缓冲文件流方法进行文件复制
try {
// 读文件流
FileReader fileReader = new FileReader(filesF[index]);
BufferedReader bufferedReader = new BufferedReader(fileReader);
// 写文件流
FileWriter fileWriter = new FileWriter(copyedFile);
BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
// 对每一行内容进行复制
String bufferString = "";
while((bufferString = bufferedReader.readLine())!=null){
bufferedWriter.write(bufferString);
}

// 关闭文件流
bufferedWriter.close();
fileWriter.close();
bufferedReader.close();
fileReader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}