如果文件内容包含10行以上,我想打印文件内容
我已尝试过此代码,但无效
import java.io.*;
public class FileExampleOne
{
public static void main(String args[]) //throws IOException
{
//open a file textual for reading
BufferedReader inFile=null;
try
{
FileReader in = new FileReader("plz.txt");
inFile = new BufferedReader(in);
int line = 0;
for(String x=inFile.readLine(); x!= null ; x=inFile.readLine())
{
line++;
// System.out.println (x);
//* it must be something here I guess ...
if(line>=10)
{
String y=inFile.readLine();
while(y!= null)
{
System.out.println( y);
y=inFile.readLine();
}
}
}
}//try
catch(FileNotFoundException e)
{
System.out.println("file error "+e.getMessage());
}
catch(IOException e)
{
System.out.println("io error "+e.getMessage());
}
finally
{
try
{
inFile.close();
System.out.println("file is now closed");
}//try
catch(IOException e)
{
System.out.println("error in finally");
}//catch
}
}
}
答案 0 :(得分:0)
你可以这样做:
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("path"));
String line = null;
int count = 0;
while ((reader.readLine()) != null && count < 11) {
count++;
}
if (count > 10) {
reader = new BufferedReader(new FileReader("path"));
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} else {
System.out.println(" the file must have at least 10 lines");
}
System.out.println("done");
} catch (Exception e) {
e.printStackTrace();
}