为什么我尝试从文件中读取时出错?

时间:2016-09-21 19:04:48

标签: java cryptography filereader filewriter

我正在编写一个程序,可以使用经典的加密方法对消息进行编码和解码。消息将从文件中读入并写入输出文件。以下程序是用java编写的,编译时没有错误。当我运行程序来测试它是否工作到目前为止我给它输入和输出文件的名称后它会遇到某种异常抛出错误。我假设问题出在代码后面的for循环中。它是一个将所有消息存储到字符数组中的循环。任何修复它的建议或其他更好的数据结构(如堆栈或队列)?

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

class CryptoProject1
{
static char eord;
static Scanner cin=new Scanner(System.in);
static char [] message=new char[10000];

public static void main (String [] args)
    throws IOException
{
    //getting the input txt file name from user
    String infilename;
    System.out.println("Please give the name of the input file.");
    infilename=cin.nextLine();
    Scanner fileread=new Scanner (new FileReader(infilename));  

    //getting the output txt file name from user
    String outfilename;
    System.out.println("Please give the name of the output file.");
    outfilename=cin.nextLine();
    PrintWriter filewrite=new PrintWriter(new FileWriter(outfilename));

    //saving the message into an array
    //construct/make it into a usable function??
    for(int i=0; i<message.length; i++)
    {
        message[i]=fileread.next().charAt(0);
    }

    //trial to make sure it reads and writes correctly
    //printing the message onto the output file
    for(int i=0; i<message.length; i++)
    {
        filewrite.print(message[i]);
    }

}   

3 个答案:

答案 0 :(得分:2)

for(int i=0; i<message.length; i++)
{
  message[i]=fileread.next().charAt(0);
}

在这里,你不知道文件长度是否与消息相同或更高,文件也可能有10个字符。你需要这样做:

for(int i=0; i<message.length; i++)
{
  if(!fileread.hasNext())
    break;
  message[i]=fileread.next().charAt(0);
}

只是一个简单的检查是否还有东西要从文件中读取,如果没有则停止阅读。

通常使用Java对象File来表示文件,而不是使用字符串来保存文件路径。例如:

private File output;
public void create file(String path)
{
    output = new File(path);
}

private BufferedWriter out = new BufferedWriter(new FileWriter(output));

答案 1 :(得分:0)

此外,无论何时写入文件,请确保通过调用close()方法将其关闭,否则其内容将无法保存

答案 2 :(得分:0)

//I ran this code without an error
//getting the input txt file name from user
String infilename;
System.out.println("Please give the name of the input file.");
infilename=cin.nextLine();
Scanner fileread=new Scanner (new FileReader(infilename));  

//getting the output txt file name from user
String outfilename;
System.out.println("Please give the name of the output file.");
outfilename=cin.nextLine();
PrintWriter filewrite=new PrintWriter(new FileWriter(outfilename));

//saving the message into an array
//construct/make it into a usable function??
for(int i=0; i<message.length; i++)
{
    if(fileread.hasNext())
    message[i]=fileread.next().charAt(0);
}
fileread.close();

//trial to make sure it reads and writes correctly
//printing the message onto the output file
for(int i=0; i<message.length; i++)
{
    filewrite.print(message[i]);
}
filewrite.close();
}