Java/File Input Output/LineNumberReader

Материал из Java эксперт
Перейти к: навигация, поиск

Convert lines into the canonical format, that is, terminate lines with the CRLF sequence.

 
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
/**
 * Convert lines into the canonical format, that is, terminate lines with the
 * CRLF sequence.
 * 
 * @author John Mani
 */
public class CRLFOutputStream extends FilterOutputStream {
  protected int lastb = -1;
  protected boolean atBOL = true; // at beginning of line?
  private static final byte[] newline = { (byte) "\r", (byte) "\n" };
  public CRLFOutputStream(OutputStream os) {
    super(os);
  }
  public void write(int b) throws IOException {
    if (b == "\r") {
      writeln();
    } else if (b == "\n") {
      if (lastb != "\r")
        writeln();
    } else {
      out.write(b);
      atBOL = false;
    }
    lastb = b;
  }
  public void write(byte b[]) throws IOException {
    write(b, 0, b.length);
  }
  public void write(byte b[], int off, int len) throws IOException {
    int start = off;
    len += off;
    for (int i = start; i < len; i++) {
      if (b[i] == "\r") {
        out.write(b, start, i - start);
        writeln();
        start = i + 1;
      } else if (b[i] == "\n") {
        if (lastb != "\r") {
          out.write(b, start, i - start);
          writeln();
        }
        start = i + 1;
      }
      lastb = b[i];
    }
    if ((len - start) > 0) {
      out.write(b, start, len - start);
      atBOL = false;
    }
  }
  /*
   * Just write out a new line, something similar to out.println()
   */
  public void writeln() throws IOException {
    out.write(newline);
    atBOL = true;
  }
}





Create LineNumberReader from FileReader

    
import java.io.FileReader;
import java.io.LineNumberReader;
class LineViewer {
  public static void main(String[] args) throws Exception {
    LineNumberReader lnr = null;
    FileReader fr = new FileReader(args[0]);
    lnr = new LineNumberReader(fr);
    String s;
    while ((s = lnr.readLine()) != null)
      System.out.println(lnr.getLineNumber() + ": " + s);
  }
}





Line Number IO

     
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
public class LineNumberIOApp {
  public static void main(String args[]) throws IOException {
    FileReader inFile = new FileReader("LineNumberIOApp.java");
    LineNumberReader inLines = new LineNumberReader(inFile);
    String inputLine;
    while ((inputLine = inLines.readLine()) != null) {
      System.out.println(inLines.getLineNumber() + ". " + inputLine);
    }
  }
}





Split Lines

    
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;
/*
 *  soapUI, copyright (C) 2004-2009 eviware.ru 
 *
 *  soapUI is free software; you can redistribute it and/or modify it under the 
 *  terms of version 2.1 of the GNU Lesser General Public License as published by 
 *  the Free Software Foundation.
 *
 *  soapUI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without 
 *  even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 *  See the GNU Lesser General Public License for more details at gnu.org.
 */

public class Utils {
  public static final String NEWLINE = System.getProperty( "line.separator" );

  public static boolean isNullOrEmpty( String str )
  {
    return str == null || str.length() == 0 || str.trim().length() == 0;
  }

  public static List<String> splitLines( String string )
  {
    try
    {
      ArrayList<String> list = new ArrayList<String>();
      LineNumberReader reader = new LineNumberReader( new StringReader( string ) );
      String s;
      while( ( s = reader.readLine() ) != null )
      {
        list.add( s );
      }
      return list;
    }
    catch( IOException e )
    {
      // I don"t think this can really happen with a StringReader.
      throw new RuntimeException( e );
    }
  }
}





Use LineNumberReader class to read file

    
 
import java.io.File;
import java.io.FileReader;
import java.io.LineNumberReader;
public class Main {
  public static void main(String[] args) throws Exception {
    File file = new File("data.csv");
    FileReader fr = new FileReader(file);
    LineNumberReader lnr = new LineNumberReader(fr);
    // lnr.setLineNumber(400);
    String line = "";
    while ((line = lnr.readLine()) != null) {
      System.out.println("Line Number " + lnr.getLineNumber() + ": " + line);
    }
    fr.close();
    lnr.close();
  }
}





Using the LineNumberReader to read a text file line by line

    
import java.io.FileReader;
import java.io.LineNumberReader;
public class Main {
  public static void main(String[] args) throws Exception {
    LineNumberReader r = new LineNumberReader(new FileReader("yourFile.txt"));
    String line = null;
    while ((line = r.readLine()) != null) {
      System.out.println(r.getLineNumber() + ": " + line);
    }
    r.close();
  }
}