说真的,咋一看,没明白你的意思。哦明白了!,你那个 class文件是不是可以建立新文件呢,你样你要用相对路径就可以了!要看看你生成文件的代码

解决方案 »

  1.   

    如果欲创建文件已存在必FAILimport java.io.*;
    public class Test {
    public static void main(String[] args){
    File f = new File("Test");
    try{
    if(f.createNewFile())
    System.out.println("OK");
    else
    System.out.println("FAIL");
    }catch(IOException e){
    System.out.println("IOException");
    }
    }
    }
      

  2.   

    我用stream做过这样的程序,他默认的就是当前目录!
      

  3.   

    import java.io.*;public class NewFile {
    private String dir = null;
    private String filename = "new.txt";    public NewFile( String filename ) {
            this( ".",filename );
        }
     
        public NewFile( String dir,String filename ) {
            this.dir = dir;
            this.filename = filename;
        }    public boolean create() {
    File f = new File( dir,filename );
    try{
    if( f.createNewFile() ) {
    System.out.println("OK");
    return true;
    }
    }
    catch( IOException e ) {
    System.out.println("IOException");
    } return false;
        } public static void main( String args[] ) {
    NewFile newFile = new NewFile( "hello.txt" );
    newFile.create();
    }
    }
      

  4.   

    import java.io.*;
    import java.lang.reflect.*;
    public class  TestDynamicClass
    {
    public static void main(String[] args) 
    {
    TestDynamicClass c = new TestDynamicClass();
    String s = c.getStringClass();
    System.out.println(s);
    } private String getStringClass(){
    try{
    String strClass = "public class DynamicClass{\n\r public static void main(String[] args) {\n\r System.out.println(\"Hello World!\"); \n\r } \n\r public static int sum(int a,int b){ \n\r  return a+b; \n\r } \n\r }";
    File file = new File("DynamicClass.java");

    if(!file.exists()){
    file.createNewFile();
    //System.out.println(file.getCanonicalPath());
    }
    FileOutputStream out = new FileOutputStream(file);
    out.write(strClass.getBytes());
    out.close();
    System.out.println(this.getClass().getPackage());
    Runtime.getRuntime().exec("javac DynamicClass.java");  file = new File("DynamicClass.class");
    while(!file.exists()){
    if(file.exists()){
    break;
    }
    } Class c = Class.forName("DynamicClass");
    Object o = c.newInstance();
    Method m = c.getMethod("sum", new Class[]{int.class,int.class});
    Integer ret = (Integer) m.invoke(o, new Object[]{new Integer(5),new Integer(15)}); //int a = DynamicClass.sum(5,6);
    //String s = String.valueOf(a);
    String s = ret.toString();
    return s;
    //return "aaa";
    }
    catch(Exception e){
    e.printStackTrace();
    return "sorry!";
    } }
    }