import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
public class ReadingfromModellerOutput {
public static void main(String args[])throws Exception
{
// BufferedReader br = new BufferedReader(new FileReader("ModellerOutput.txt"));
LineNumberReader reader= new LineNumberReader(new FileReader("ModellerOutput1.txt"));
String line;
while ((line = reader.readLine()) != null)
{
if(line.startsWith("Summary"))
{
System.out.println(reader.getLineNumber());
for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
{
System.out.println(reader.getLineNumber());
writeTofile(line);
}
}
}
}
public static void writeTofile(String line)
{
//System.out.println(reader.getLineNumber());
// for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
// {
// System.out.println(reader.getLineNumber());
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Output_1.txt"), true));
System.out.println("Hi");
bw.write(line);
bw.newLine();
bw.close();
}
catch (Exception e) {}
}
}
我正在尝试编写一个代码,从一行开头的文本文件中提取50行 限制违规行为摘要: 上面的代码写的是同一行限制违规的摘要: 50次。请帮忙。
答案 0 :(得分:3)
System.out.println(reader.getLineNumber());
line = reader.readLine(); // You forgot to put this.
writeTofile(line);
另外,请不要忘记在break;
循环后(for
内)放置if
,这样您就不会在50 lines
后写更多行了}。
答案 1 :(得分:1)
我认为你应该在for循环中读取行。
但是你必须再次检查文件的结尾。看看这个实现:
String line = reader.readLine();
while (line != null) {
if (line.startsWith("Summary")) {
for (int i = 0; i < 50; i++) {
line = reader.readLine();
if (line != null) {
writeTofile(line);
} else {
break;
}
}
}
}
答案 2 :(得分:1)
line = reader.readLine();
上面的行应该在for循环中。
答案 3 :(得分:0)
试试这个程序。使用适当的Break语句
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.LineNumberReader;
public class ReadingfromModellerOutput {
public static void main(String args[])throws Exception
{
// BufferedReader br = new BufferedReader(new FileReader("ModellerOutput.txt"));
LineNumberReader reader= new LineNumberReader(new FileReader("ModellerOutput1.txt"));
String line;
while ((line = reader.readLine()) != null)
{
if(line.startsWith("Summary"))
{
System.out.println(reader.getLineNumber());
for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
{
System.out.println(reader.getLineNumber());
writeTofile(line);
}
break;
}
}
}
public static void writeTofile(String line)
{
//System.out.println(reader.getLineNumber());
// for(int i=reader.getLineNumber();i<=(reader.getLineNumber()+50);i++)
// {
// System.out.println(reader.getLineNumber());
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Output_1.txt"), true));
System.out.println("Hi");
bw.write(line);
bw.newLine();
bw.close();
}
catch (Exception e) {}
}
}