代码如下:
String url= "./src/test/org/name/a.txt";
File f = new File(url);
if(f.exists()){
System.out.println("i am exist");
}
PrintWriter pw = null;
try {
pw = new PrintWriter(f,"UTF-8");
pw.write("hello world");
pw.flush();
} catch (IOException ex) {
ex.printStackTrace();
}finally{
if (pw != null) {
try {
pw.close();
} catch (Exception e1) {
}
}
}
我想在new的时候,url不要src,我试了getResource却不能写入hello world,有高手能解决这一问题吗,url中不包含src并且让a.txt能写hello world

解决方案 »

  1.   

    System.getProperty("user.dir"),这个可以得到你的项目生成后的jar的实际目录,你要写a.txt,就不要把a.txt放到src里,放到你的磁盘的目录下,这样用这个就可以了,
      

  2.   


            String url= "a.txt";
            File f = new File(url);
            if(f.exists()){
                System.out.println("i am exist");
            }
            PrintWriter pw = null;
            try {
                pw = new PrintWriter(f,"UTF-8");
                pw.write("hello world");
                pw.flush();
            } catch (IOException ex) {
                ex.printStackTrace();
            }finally{
                if (pw != null) {
                    try {
                        pw.close();
                    } catch (Exception e1) {
                    }
                }
            }把文件放到src的父目录中,就好了!
      

  3.   

    问题是不能移动a.txt,那该怎么办
      

  4.   

    String path= "./src";
    String childPath="test/org/name/a.txt"
    File f = new File(path,childPath);
    OK??
      

  5.   

    File file= new File("./src");
    String childPath="test/org/name/a.txt"
    File f = new File(file,childPath);也可以的
      

  6.   

    搞不清当前目录的时候
    system.out.println(new File(".").absolutePath());
    就知道了
      

  7.   

    要使用绝对路径创建文件夹,如果你原来就有这个文件夹就可以用./test/org/name/a.txt
    没有的话就要判断并创建文件夹,然后通过这个绝对路径创建文件public class Test {
    public static void main(String[] args) {
    String url = "test/org/name";
    File folder = new File(url);
    if (!folder.exists()) { // 创建文件夹
    folder.mkdirs();
    } // 用文件夹绝对路径 + 文件 拼接绝对路径
    String filepath = folder.getAbsolutePath();
    File file = new File(filepath + "/a.txt");
    //file.getAbsolutePath() ---->  E:\CL\tempworkspace\csdnTest\test\org\name\a.txt

    PrintWriter pw = null;
    try {
    pw = new PrintWriter(file, "UTF-8");
    pw.write("hello world!"); } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    } finally {
    if (pw != null)
    pw.close();
    }