当前页面: 开发资料首页 → J2SE 专题 → 文件的路径问题
文件的路径问题
摘要: 文件的路径问题
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
try{
//File f = new File("/");
//System.out.println(f.getAbsolutePath());
FileInputStream fis = new FileInputStream("CopyFile.java");
FileOutputStream fos = new FileOutputStream("temp.txt");
int read = fis.read();
while(read!=-1)
{
fos.write(read);
read = fis.read();
}
fis.close();
fos.close();
}catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
结果是找不到文件CopyFile.java,我本来的意思是指当前目录,后来加了上面注释掉的两行
File f = new File("/");
System.out.println(f.getAbsolutePath());
显示当前目录居然是在D:下面,可我的程序明明不在D盘下面啊
去看JDK帮助文档
jdk是不是在D盘啊?
我运行的结果显示system.out出来的是G:/
我的工程文件在G:/
程序没错。
File f = new File("/");
System.out.println(f.getAbsolutePath());
可以正常显示文件所在盘符
找不到CopyFile.java,可能是拼写错误,或该文件不存在,或与class文件不在同一目录下
new File("/");
是指根目录,在windows系统下,就是所在逻辑盘的根,比如 file://c:/ file://d:/。
如果我的java文件在D:/Program Files/eclipse/workspace/OneBook/src这里,我想把文件放这里,那地址该怎么写啊
Mark~
FileInputStream fis = new FileInputStream("D://Program Files//eclipse//workspace//OneBook//srcCopyFile.java");
回楼上的,我现在就是照你那么做的,可这么写不是换个地方的话,又要该,很不方便啊
请参考http://community.csdn.net/Expert/topic/4698/4698215.xml?temp=.3442346
用相对路径吧,相对于你java运行时候的位置
比如你的项目在d:/app,运行时候是在d:/app里运行的java命令,相对路径就是相对于这里的路径。
比如"./example"就是d:/app/example
File f = new File("/");
这里有错误
java中的/具有特殊的含义,所以要使用文件路径必需使用转义字符//
File f=new File("/");
我这里有一段程序,能拷贝一个文件夹下的所有文件和文件夹
import java.io.*;
public class Filecopy {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
if (args.length == 0)
args = new String[] { "g://2", "g://1" };
File frompath = new File(args[0]);
File topath = new File(args[1]);
String[] fromlist = frompath.list();
for (int i = 0; i < fromlist.length; i++) {
File fromfile = new File(frompath.getPath(), fromlist[i]);
File tofile = new File(topath.getPath(), fromlist[i]);
if (fromfile.isDirectory()) {
tofile.mkdirs();
System.out.println( fromfile.getCanonicalPath());
main(new String[] { fromfile.getPath(), tofile.getPath() });
}
else {
int ch;
byte[] b = new byte[256];
RandomAccessFile fin = new RandomAccessFile(fromfile, "r");
RandomAccessFile fout = new RandomAccessFile(tofile, "rw");
ch = fin.read(b);
while (ch != -1) {
fout.write(b);
ch = fin.read(b);
}
fin.close();
fout.close();
}
}
}
}