如何使用java在unix上移动文件?
我用netbeans编写java。我想移动文件和创建文件。当我在netbeans上运行程序时,它可以工作。创建和移动文件。但当我在jar上运行程序时,它不会复制或移动。我给permisson jar和文件读写。但它不起作用。我用root用户打开jar。我怎样才能解决这个问题 这是我要复制的代码如何使用java在unix上移动文件?,java,netbeans,jar,file-copying,Java,Netbeans,Jar,File Copying,我用netbeans编写java。我想移动文件和创建文件。当我在netbeans上运行程序时,它可以工作。创建和移动文件。但当我在jar上运行程序时,它不会复制或移动。我给permisson jar和文件读写。但它不起作用。我用root用户打开jar。我怎样才能解决这个问题 这是我要复制的代码 package aaa; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream;
package aaa;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class MoveFolder
{
public int copy(String from,String where )
{
int onay=0;
File srcFolder = new File(from);
File destFolder = new File(where);
//make sure source exists
if(!srcFolder.exists()){
System.out.println("Directory does not exist.");
onay = -1;
// JOptionPane.showMessageDialog(null, "Directory does not exist.");
}else{
try{
copyFolder(srcFolder,destFolder);
}catch(IOException e){
e.printStackTrace();
onay = -1;
// JOptionPane.showMessageDialog(null, "Was not Copied.");
}
}
System.out.println("Done");
return onay;
}
public void copyFolder(File src, File dest)
throws IOException{
if(src.isDirectory()){
//if directory not exists, create it
if(!dest.exists()){
dest.mkdir();
System.out.println("Directory copied from "
+ src + " to " + dest);
// JOptionPane.showMessageDialog(null, "Directory copied from " + src + " to " + dest);
}
//list all the directory contents
String files[] = src.list();
for (String file : files) {
//construct the src and dest file structure
File srcFile = new File(src, file);
File destFile = new File(dest, file);
//recursive copy
copyFolder(srcFile,destFile);
}
}else{
//if file, then copy it
//Use bytes stream to support all file types
InputStream in = new FileInputStream(src);
OutputStream out = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
//copy the file content in bytes
while ((length = in.read(buffer)) > 0){
out.write(buffer, 0, length);
}
in.close();
out.close();
System.out.println("File copied from " + src + " to " + dest);
// JOptionPane.showMessageDialog(null, "File copied from " + src + " to " + dest);
}
}
}
为什么要用IO流复制文件?为什么不直接做呢
File f; // bla bla init
File otherFile;
f.renameTo(otherFile);
此外,您需要对尝试移动(到)的文件具有读写权限,而不是对正在执行的JAR具有读写权限…请发布代码、启动程序所用的命令并打印/收到的异常。我编辑了我的问题。没关系。我认为问题是关于权限的。您正在复制到一个不存在的目录吗?您的代码不包含
main()
方法。请用代码编辑您的问题,重新创建您的确切问题,以便我们可以帮助您。特别是,我们需要知道如何告诉这个类要复制哪些文件。另外,这些文件在您的文件系统中的位置是什么?因为重命名为移动文件而不是复制它。我编辑我的问题并使用此类。它可以在netbeans上运行,但不能在jar上运行。请帮忙。