【发布时间】:2017-10-12 02:48:58
【问题描述】:
我正在创建以下程序,它读取一个 text.file 并根据给定的参数打印出某些内容。如果用户输入“运行配置文件 text.txt”,我希望它逐行打印出文件。如果用户输入“run Profile text.txt 5”,则应打印出前 5 行。我编写了以下程序:
import java.util.*;
import java.io.*;
public class Profile{
public static String file;
public static int len;
public static Profile a;
public static Profile b;
//Method to read whole file
static void wholeFile(String file){
Scanner in = new Scanner(file);
int lineNumber = 1;
while(in.hasNextLine()){
String line = in.nextLine();
System.out.println("/* " + lineNumber + " */ " + line);
lineNumber++;
}
in.close();
}
//Method to read file with line length
static void notWholeFile(String file, int len){
Scanner in = new Scanner(file);
int lineNumber = 1;
while(in.hasNextLine() && lineNumber <= len){
String line = in.nextLine();
System.out.println("/* " + lineNumber + " */ " + line);
lineNumber++;
}
in.close();
}
Profile(String file){
this.file = file;
}
Profile(String file, int len){
this.file = file;
this.len = len;
notWholeFile(file, len);
}
public static void main(String[] args){
Scanner in = new Scanner (System.in);
if (args.length == 1){
file = args[0] + "";
a = new Profile(file);
wholeFile(file);
}
if (args.length == 2){
file = args[0] + "";
len = Integer.parseInt(args[1]);
b = new Profile(file, len);
notWholeFile(file, len);
}
}
}
出于测试目的,我在我的目录中包含了一个名为“text.txt”的 .txt 文件,其中包含以下文本:
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
blah blah blah blah blah blah blah
我是 java 的初学者,但相信不应该有任何错误。但是,当我输入“run Profile text.txt 5”时,我得到以下输出:
> run Profile text.txt 5
/* 1 */ text.txt
/* 1 */ text.txt
>
为什么我不能打印出“blah blah”行?我读取 .txt 文件的方式有错误吗?如何访问此文本文件中的行?任何建议都会有所帮助。
【问题讨论】:
-
是时候调试了。一个建议,将
Profile类与Main类分开,将Profile a, b移动到局部变量 -
我不明白这两个
Profile构造函数的目的,因为它们似乎没有被使用。 -
我确定,您的扫描仪读取的是字符串文件而不是实际文件。还要从构造函数中删除 notWholeFile
标签: java filereader