2016-03-04 85 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(); 
    } 

} } 
相關問題