2016-03-04 80 views
0
import java.io.*; 
class C{ 
    public static void main(String args[])throws Exception{ 
     FileInputStream fin=new FileInputStream("C.java"); 
     FileOutputStream fout=new FileOutputStream("M.java"); 
     int i=0; 
     while((i=fin.read())!=-1){ 
     fout.write((byte)i); 
     } 
     fin.close(); 
    } 
} 

我尝试创建文件来读取和写入代码将存储在哪里。在我的情况下,它被存储在C驱动器(我的程序,我创建它只有读写文件)。我试图运行文件程序,我得到错误FileNotFoundException

我的程序成功生成,但没有输出 应用程序名称 - javaprogram 包的名字 - 包

里面包我已经把两个文件c.txtm.txt 我甚至想知道的是,我们有.java文件(我与c.txtm.txt而非.java)试图

这是我得到错误

init: 
deps-jar: 
Compiling 1 source file to C:\Users\user\Documents\NetBeansProjects\JavaApplication1\build\classes 
compile-single: 
run-single: 
Exception in thread "main" java.io.FileNotFoundException: file (The system cannot find the file specified) 
     at java.io.FileInputStream.open(Native Method) 
     at java.io.FileInputStream.<init>(FileInputStream.java:106) 
     at java.io.FileInputStream.<init>(FileInputStream.java:66) 
     at javaapplication1.C.main(C.java:20) 
+1

什么仰视[FileNotFoundException异常(https://docs.oracle.com/javase/7/docs/api/java/io/FileNotFoundException.html)? – Stefan

+0

您尝试读取的文件是否存在?在同一个包里面存在 – Genzotto

+0

。 –

回答

0

下面你从这个Link缺少的东西文件对象

class C { 

public static void main(String args[]) 
{ 
    try 
    { 
     File f1 = new File("C.java"); 
     File f2 = new File("M.java"); 

     FileInputStream in = new FileInputStream(f1); 
     FileOutputStream out = new FileOutputStream(f2); 

     byte[] buf = new byte[1024]; 
     int len = 0; 
     while ((len = in.read()) > 0) 
     { 
      out.write(buf, 0, len); 
     } 

     in.close(); 
     out.close(); 
    } catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 

} 
} 

这样做的另一种优雅的方式是 下载Commons IO使用代码,并将其添加到项目库中,然后使用下面的代码。

class C { 

public static void main(String args[]) throws Exception 
{ 
    try 
    { 
     File f1 = new File("C.java"); 
     File f2 = new File("M.java"); 

     FileUtils.copyFile(f1, f2); 

    } catch (FileNotFoundException e) 
    { 
     e.printStackTrace(); 
    } catch (IOException e) 
    { 
     e.printStackTrace(); 
    } 

} } 
相关问题