「java移文件」java文件迁移

博主:adminadmin 2023-01-02 10:12:07 1084

今天给各位分享java移文件的知识,其中也会对java文件迁移进行解释,如果能碰巧解决你现在面临的问题,别忘了关注本站,现在开始吧!

本文目录一览:

Java中如何进行文件(及文件夹)的新建,移动,删除等?给出代码

File

F=new

File(路径);/通过将给定路径名字符串转换为抽象路径名来创建一个新

File

实例。

F.delete();//删除此抽象路径名表示的文件或目录。

文件的移动的话,得通过输入输出流

FileInputStream

FI=new

FileInputStream(F);

FileOutputStream

FO=new

FileOutputStream(F);

wile(FI.read()!=EOF)

{

FO.write();

}

java中文件移动问题,file.move

File的renameTo()就是移动。

它会删掉原来下面的文件,然后在你指定的路径创建一个文件。

前提你要保证指定的路径存在,不存在就先创建。

Java怎么移动文件夹里的文件到指定文件

是的,用File类的renameTo方法即可,注意目标文件名一定要合法,否则失败!

/**

* 移动文件到指定目录

*

* @param oldPath

* String 如:c:/fqf.txt

* @param newPath

* String 如:d:/fqf.txt

*/

public static void moveFile(String oldPath, String newPath) {

copyFile(oldPath, newPath);

delFile(oldPath);

}

/**

* 移动文件到指定目录

*

* @param oldPath

* String 如:c:/fqf.txt

* @param newPath

* String 如:d:/fqf.txt

*/

public static void moveFolder(String oldPath, String newPath) {

copyFolder(oldPath, newPath);

delFolder(oldPath);

}

java io 移动文件

public void moveFile() throws Exception {

Scanner scan = new Scanner(System.in);

System.out.println("请输入源路径:");//D:/test/a.txt

String uDisk = scan.nextLine();

File file = new File(uDisk);

if ((file.exists())) {

System.out.println("请输入目标路径:");//移动的位置

String targetFolder = scan.nextLine();

File target = new File(targetFolder);

if (!target.exists()) {

if (!target.mkdir()) {

throw new Exception("创建目标目录失败");

}

} else if (!target.isDirectory()) {

throw new Exception("与目标目录同名的文件已经存在");

}

File[] temp=null;

if(file.listFiles()==null){

temp= new File[]{file};

}else{

temp = file.listFiles();

}

if ((temp != null) (temp.length 0)) {

int i = 0;

for (int length = temp.length; i length; i++) {

if (!temp[i].isDirectory()) {

String fileName = temp[i].getName();

File t = new File(targetFolder + File.separator

+ fileName);

if (!t.createNewFile()) {

throw new Exception("创建输出文件失败");

}

FileOutputStream out = new FileOutputStream(t);

FileInputStream in = new FileInputStream(temp[i]);

byte[] buffer = new byte[256];

while (in.read(buffer) 0) {

out.write(buffer);

}

}

}

}

}

}

这个可以移动文件夹下所有文件,也可以移动单个文件

怎样使用java编程实现文件的剪切/移动

可以通过BufferedReader 流的形式进行流读取,之后通过readLine方法获取到的内容,之后通过if判断来实现在某些特定位置的内容的剪切和移动操作。

举例:

BufferedReader bre = null;

OutputStreamWriter pw = null;//定义一个流

try {

String file = "D:/test/test.txt";

bre = new BufferedReader(new FileReader(file));//此时获取到的bre就是整个文件的缓存流

pw = new OutputStreamWriter(new FileOutputStream(“D:/test.txt”),"GBK");//确认流的输出文件和编码格式,此过程创建了“test.txt”实例

while ((str = bre.readLine())!= null) // 判断最后一行不存在,为空结束循环

{

if(str.indexOf("排除")0){//判断是否需要舍弃

pw.write(str);//将要写入文件的内容,可以多次write

}

}

bre.close();//关闭流

pw.close();//关闭流

解释:以上方法是实现的删除,if中的条件改变下,即可实现其余的功能。

备注:文件流用完之后必须及时通过close方法关闭,否则会一直处于打开状态,直至程序停止,增加系统负担。

关于java移文件和java文件迁移的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。