2013-11-25 52 views
0

我正試圖用Java對Java進行簡單的文件加密。沒有什麼嚴肅和硬核,只是非常基本。現在我需要通過在文件的每個字節中加5來對文件進行編碼。程序提示用戶輸入輸入文件名稱和輸出文件名稱,並將輸入文件的加密版本保存到輸出文件。Java文件加密,無法讓它接受文件輸入

這裏是我的代碼

import java.util.Scanner; 
import java.io.*; 

public class EncryptFiles { 
    public static void main(String[] args) throws IOException { 

     Scanner input = new Scanner(System.in); 

     System.out.print("Enter a file to encrypt: "); 

     FileInputStream in = new FileInputStream(input.next()); 
    // BufferedInputStream in = new BufferedInputStream(new FileInputStream(new File(input.next()))); 

     System.out.print("Enter the output file: "); 

     FileOutputStream output = new FileOutputStream(input.next()); 
    // BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(new File(input.next()))); 

     int value; 

     while ((value = in.read()) != -1) { 
      output.write(value + 5); 
     } 

     input.close(); 
     output.close(); 

    } 
} 

我已經DOEN正規的FileInputStream還有的BufferedInputStream和他們兩個給我同樣的錯誤。

> Exception in thread "main" java.io.FileNotFoundException: Me.txt (The 
> system cannot find the file specified) at 
> java.io.FileInputStream.open(Native Method) at 
> java.io.FileInputStream.<init>(FileInputStream.java:146) at 
> java.io.FileInputStream.<init>(FileInputStream.java:101) at 
> EncryptFiles.main(EncryptFiles.java:10) Java Result: 1 

我把文件Me.txt在C:目錄下,我已經把文件我也試過把它在Java src文件夾。我試圖輸入確切的文件路徑,沒有任何工作。我已經做到了這樣C:/Users/Richard/Documents/Me.txt並且像這樣C:\Users\Richard\Documents\Me.txt但是不管我如何嘗試它,我都會得到相同的錯誤。

感謝今後的援助:)

+0

我已經試過了,以及,出現同樣的錯誤方式 –

+0

剛剛嘗試過,仍然是一個錯誤 –

+2

對我來說工作得很好。 Me.txt實際上是Me.txt.txt嗎?默認情況下,Windows隱藏文件擴展名,所以如果你命名一個文件Me.txt,它實際上將被命名爲Me.txt.txt – Vitruvius

回答

1

嘗試改變你實例化FileInputStreamFileOutputStream

FileInputStream in = new FileInputStream(new File(input.nextLine())); 

FileOutputStream in = new FileOutputStream(new File(input.nextLine())); 

,並使用完整路徑作爲輸入像C:/Users/Richard/Documents/Me.txt

0

我會嘗試這樣的事情 -

String fileInPath = input.next().trim(); 
System.out.println("Opening file " + fileInPath); 
FileInputStream in = new FileInputStream(fileInPath); 

我可能會使用的東西更多類似這樣的自己;你應該總是關閉你的資源。

String fileInPath = input.next().trim(); 
System.out.println("Opening file " + fileInPath); 
FileInputStream in = null; 
try { 
    File fileIn = new File(fileInPath); 
    if (fileIn != null && fileIn.canRead()) { 
    in = new FileInputStream(fileIn); 
    } else { 
    System.out.println("Could not open file " + fileInPath); 
    } 
} catch (FileNotFoundException e) { 
} finally { 
    if (in != null) { 
    try { 
     in.close(); 
    } catch (IOException e) { 
    } 
    } 
} 
+0

謝謝你的幫助,我已經通過有用的評論:) –