java中读取和替换行
我试图将 file.txt 逐行读入 java,然后当一行是“foo”时,我将其后面的行设置为“lineAfterFoo”,然后将其输出给用户。
我的 Java 代码...
public void main(String[] args) throws IOException {
try {
FileReader someFile = new FileReader("file.txt");
BufferedReader input = new BufferedReader(someFile);
int i = 0;
String[] line;
line = new String[10];
line[i] = input.readLine();
while(line[i] != null) {
line[i] = input.readLine();
if (line[i] == "foo") {
i = i + 1;
line[i] = "lineAfterFoo";
}
i = i + 1;
}
for (int number = 1; number < i; number++) {
System.out.println(line[number]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
File.txt
1
2
3
foo
HopeFullyThisWillChange
5
6
7
8
9
10
错误...
java.lang.NoSuchMethodError: main
Exception in thread "main"
感谢您的帮助!
I'm attempting to read the file.txt into java line by line and then when a line is "foo" I set the line after it to be "lineAfterFoo" then output that to the user.
My Java Code....
public void main(String[] args) throws IOException {
try {
FileReader someFile = new FileReader("file.txt");
BufferedReader input = new BufferedReader(someFile);
int i = 0;
String[] line;
line = new String[10];
line[i] = input.readLine();
while(line[i] != null) {
line[i] = input.readLine();
if (line[i] == "foo") {
i = i + 1;
line[i] = "lineAfterFoo";
}
i = i + 1;
}
for (int number = 1; number < i; number++) {
System.out.println(line[number]);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
File.txt
1
2
3
foo
HopeFullyThisWillChange
5
6
7
8
9
10
The Error...
java.lang.NoSuchMethodError: main
Exception in thread "main"
Thanks for any help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
main
方法必须是static
:编辑 - 解决实际问题
循环只运行一次,因为在第一次通过
while
主体之后,i
将等于1
。此时line[1]
为 null,因为您还没有读入任何内容。这是所使用的典型习惯用法(注意变量名称的变化):The
main
method must bestatic
:Edit - onto solving the real problem
The loop only runs once because, after the first pass through the
while
body,i
will be equal to1
. At that pointline[1]
is null, because you haven't read anything into it. Here's the typical idiom used instead (note the changes in variable names):该错误与您的代码根本无关,您只是试图执行错误的类。检查您的 IDE 配置,并使用
java MyMainClass
在命令行上进行测试。This error is not related to your code at all, you're simply trying to execute the wrong class. Check your IDE configuration, and test on the command line with
java MyMainClass
.main
不需要是static
吗?Doesn't
main
need to bestatic
?