繁体   English   中英

尝试从文件中读取文件时为什么会出现错误?

[英]Why am I getting an error when it tries to read from the file?

我正在编写一个程序,可以使用经典的加密方法对消息进行编码和解码。 该消息将从文件中读取并写入输出文件。 以下程序是用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]);
    }

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

另外,每当写入文件时,请确保通过调用close()方法将其关闭,否则将不保存其内容

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM