質問:コマンドライン引数から既存のテキストファイルのリストを受け入れ、 "Master.txt"内のすべてのファイルの内容を連結するJavaプログラムを作成します。 。コマンドライン引数から既存のテキストファイルのリストを受け取るJavaプログラム
私のコードは、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());
}
}
}
出力:fin
が値を割り当てられたりしていない場合
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
はどのようにチェックしますか?
これは、finとfoutもnullに初期化されている場合にのみ機能します。 – finnw