我想使用main方法数组从两个或多个文件中读取文本。可能吗? (我的代码可能有点奇怪,因为我是初学者)
这是我的代码。
public static void main(String[] args) throws IOException {
if(args.length != 1)
{
System.out.println("wrong number of arguments");
System.exit(1);
}
args[0] = "data.txt";
args[1] = "data2.txt";
BufferedReader file = new BufferedReader(new FileReader(args[0],args[1]));
int NumberofRows =0, NumberofCharacter =0;
while(true)
{
String row = file.readLine();
if(row == null)
break;
NumberofRows++;
NumberofCharacter = NumberofCharacter + row.length();
}
System.out.println("The files "+" data.txt " + " and " "data2.txt "+ "contains "+ NumberofRows+ "rows and NumberofCharacter contains"+
NumberofCharacter +" character");
file.close();
答案 0 :(得分:3)
@Lena:我不明白为什么你会在main方法中影响args []的值?
args[0] = "data.txt";
args[1] = "data2.txt";
相反,您可以传递文件'执行main时args []中的名称,并测试args [] .length< 1,如果要读取两个或更多文件,则导致args [] .length!= 1将始终为true。所以@ugurdonmez说:你可以创建一个具有相同大小的args的BufferedReader数组。
public static void main(String[] args)throws IOException {
if(args.length <1)
{
System.out.println("wrong number of arguments");
System.exit(1);
}
for(int i=0; i<args.length; i++)
{
BufferedReader file = new BufferedReader(new FileReader(args[i]));
int NumberofRows =0, NumberofCharacter =0;
while(row = file.readLine()) !=null)
{
String row = file.readLine();
NumberofRows++;
NumberofCharacter = NumberofCharacter + row.length();
}
}
System.out.println("The files "+" data.txt " + " and " "data2.txt "+ "contains "+ NumberofRows+ "rows and NumberofCharacter contains"+
NumberofCharacter +" character");
file.close();
}
}
答案 1 :(得分:2)
public static void main(String[] args)throws IOException {
if (args.length != 1) {
System.out.println("wrong number of arguments");
System.exit(1);
}
args[0] = "data.txt";
args[1] = "data2.txt";
for (int i = 0; i < args.length; i++) {
BufferedReader file = new BufferedReader(new FileReader(args[i]));
int NumberofRows = 0, NumberofCharacter = 0;
while (true) {
String row = file.readLine();
if (row == null)
break;
NumberofRows++;
NumberofCharacter = NumberofCharacter + row.length();
}
file.close();
}
}
答案 2 :(得分:2)
答案 3 :(得分:1)
您可以使用相同大小的args创建BufferedReader数组。然后你可以用循环构造它们。
答案 4 :(得分:0)
String row = "";
while(row = file.readLine()) !=null)
{
System.out.println(row);
NumberofRows++;
NumberofCharacter += row.length();
}
你可能想在阅读文件时考虑这种方法,不要强迫程序从文件中读取行。这有时会抛出异常。