Java文件加密,无法让它接受文件输入

时间:2013-11-25 04:28:33

标签: java encryption file-io inputstream outputstream

我正在尝试使用Java进行简单的文件加密。没有什么是严肃和硬核的,只是非常基本的。现在我需要通过向文件中的每个字节添加5来对文件进行编码。程序提示用户输入输入文件名和输出文件名,并将输入文件的加密版本保存到输出文件中。

这是我的代码

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();

    }
}

我已经完成了常规的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但是无论我如何尝试,我都会得到同样的错误。

感谢您将来的协助:)

2 个答案:

答案 0 :(得分:1)

尝试更改将FileInputStreamFileOutputStream实例化为

的方式
FileInputStream in = new FileInputStream(new File(input.nextLine()));

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

并使用完整路径作为输入,如C:/Users/Richard/Documents/Me.txt

答案 1 :(得分: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) {
    }
  }
}