本帖最后由 李健09 于 2013-9-11 21:06 编辑
- <p><p>package com.IO;
- import java.io.*;
- public class LineNumberReaderDemo
- {
- public static void main(String[] args) throws IOException
- {
- FileReader fr=new FileReader("F:\\java\\Workspaces\\eclipse_English\\day19\\sinian.txt");</p><p> //FileReader fr=new FileReader("F:\\java\\Workspaces\\eclipse_English\\day19\\src\\com\\IO\\zhuangshihejicheng.java");
- //此处改为.java文件又为什么没有最后一行空白行呢?
- LineNumberReader linr=new LineNumberReader(fr);
- String line=null;
- linr.setLineNumber(100);
- while((line=linr.readLine())!=null)
- {
- sop(linr.getLineNumber()+":"+line);
- }
- linr.close();
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }</p></p>
复制代码 我的文本文件一共有6行但是读取之后会有一行空白行出来,也就是会多出来一个107行的空白行,我想把这个空白行去掉怎么做,我根据老师课件自己写了一个但是输出的不对输出的只有2,4,6这三行代码如下- package com.IO;
- import java.io.*;
- class LineNumReader extends Reader
- {
- private Reader r;
- LineNumReader(Reader r)
- {
- this.r =r;
- }
- public String ReadLine() throws IOException
- {
- StringBuilder sb=new StringBuilder();
- int ch=0;
- while((ch=r.read())!=-1)
- {
- if(ch=='\r')
- continue;
- if(ch=='\n')
- return sb.toString();
- else
- sb.append((char)ch);
- }
- if(sb.length()!=0)
- return sb.toString();
- return null;
- }
- public int read(char[] cbuf, int off, int len) throws IOException
- {
- return r.read(cbuf, off, len);
- }
- public void close() throws IOException
- {
- r.close();
- }
- public void myClose() throws IOException
- {
- r.close();
- }
- }
- public class LineNumberReaderDemo2
- {
- public static void main(String[] args) throws IOException
- {
- FileReader fr=new FileReader("F:\\java\\Workspaces\\eclipse_English\\day19\\sinian.txt");
- LineNumberReader linr=new LineNumberReader(fr);
- LineNumReader linrr=new LineNumReader(linr);
- String line=null;
- String liner=null;
- linr.setLineNumber(100);
- while((line=linr.readLine())!=null&&(liner=linrr.ReadLine())!=null)
- {
- sop(linr.getLineNumber()+":"+line);
- }
- linr.close();
- linrr.close();
- }
- public static void sop(Object obj)
- {
- System.out.println(obj);
- }
- }
-
-
-
复制代码 |