Java程序,它接受来自命令行参数的现有文本文件列表

0 java

问题:编写一个Java程序,它接受来自命令行参数的现有文本文件列表,并连接"Master.txt"中所有文件的内容.

我的代码在测试4时出错endsWith(".txt").请让我知道如何纠正它.

import java.io.*;
class FileConcat
{
 public static void main(String[] args)
 {
  FileOutputStream fout;
  FileInputStream fin,fin1;
  File f;
  int b; 
  try
  {
   //open Master file
   try
   {
    fout=new FileOutputStream("Master.txt"); 
   }
   catch(Exception e)
   {
    System.out.print(e.getMessage());
   }
   //traverse all args, check if valid text file, if yes, concatinate
   for(int j=0;j<args.length;j++)
   {
    f=new File(args[j]);
    if(f.isFile()==true)
    {
     if((args[j].endsWith(".txt"))==true)
     {
      try
      {
       fin=new FileInputStream(args[j]);
      }
      catch(Exception e)
      {
       System.out.print("Error Opening "+args[j]);
      }
      while((b=fin.read())!=-1)
      {
       char ch=(char) b;
       fout.write(ch);
      }
     }
    fin.close();
    }
   }
   fout.close();
   fin1=new FileInputStream("Master.txt"); 
   while((b=fin1.read())!=-1)
   {
    char ch=(char) b;
    System.out.print(ch);
   }
   fin1.close();
  }
  catch(Exception e)
  {
   System.out.println(e.getMessage());
  }
 }
}
Run Code Online (Sandbox Code Playgroud)

输出:

C:\j2sdk1.4.1_01\bin>javac FileConcat.java
FileConcat.java:38: variable fin might not have been initialized
                                                while((b=fin.read())!=-1)
                                                         ^
FileConcat.java:41: variable fout might not have been initialized
                                                        fout.write(ch);
                                                        ^
FileConcat.java:44: variable fin might not have been initialized
                                fin.close();
                                ^
FileConcat.java:47: variable fout might not have been initialized
                        fout.close();
                        ^
4 errors
Run Code Online (Sandbox Code Playgroud)

如何检查是否fin分配了值?

moo*_*dow 5

问题是你在声明它们时根本没有为fin和fout分配任何东西,你只在try {}块中分配它们,随后使用它们的代码在try {}块之外; 因此,如果在try {}块中抛出异常,程序将继续运行,并尝试使用未初始化的值.

你的选择是:

  • 移动代码尝试在初始化它们的try {}块中使用这些变量
  • null在声明它们时分配给这些变量,并放置试图在if (variable != null) {}块中使用它们的代码.
  • 使catch()子句执行一些操作,以保证否则尝试使用未初始化的变量的代码不会执行,例如退出程序
  • 只是摆脱try .. catch子句并将整个方法声明为抛出这些异常