2013-02-07 72 views
6

Tôi thích để loại bỏ tất cả các ký tự xuống dòng (đối với cả hai \ n và \ r \ n) từ một java.io.InputStream, khi đọc một tập tin, phương pháp tương ứng trông như thế này:Loại bỏ ký tự newline từ InputStream

/** 
* @param target {@linkplain File} 
* @return {@linkplain InputStream} 
* @throws Exception 
*/ 
protected InputStream initInput(final File file) 
    throws Exception { 
    InputStream stream = null; 
    try { 
     if (file.isDirectory()) { 
      // throw exception 
     } 
     if (!file.exists()) { 
      // throw another exception 
     } 
     // 
     // *remove newlines here* 
     // 
     stream = new FileInputStream(file); 

    } catch (FileNotFoundException e) { 
     // throw another exception 
    } 
    return stream; 
} 

Trả lời

6

Bạn có thể có sự cấy ghép của riêng bạn java.io.FileInputStream và ghi đè các phương pháp đọc theo cách bạn nhảy qua \r\n trong khi đọc.

Hier là thực hiện mẫu (không có bất kỳ xử lý lỗi)

import java.io.File; 
import java.io.FileDescriptor; 
import java.io.FileInputStream; 
import java.io.FileNotFoundException; 
import java.io.IOException; 

public class NoNewLineFileInputStream extends FileInputStream { 

    public NoNewLineFileInputStream(String filepath) throws FileNotFoundException { 
     super(filepath); 
    } 

    public NoNewLineFileInputStream(File file) throws FileNotFoundException { 
     super(file); 
    } 

    public NoNewLineFileInputStream(FileDescriptor filedescriptor) { 
     super(filedescriptor); 
    } 

    @Override 
    public int read(byte[] b) throws IOException { 
     return this.read(b, 0, b.length); 
    } 

    @Override 
    public int read(byte[] b, int off, int len) throws IOException { 
     int n = 0, c; 
     do { 
      c = this.read(); 
      if(c != -1) { 
       b[off + n] = (byte) c; 
       n++; 
       len--; 
      } else { 
       return c; 
      } 
     } while(c != -1 && len > 0); 
     return n; 
    } 


    @Override 
    public int read() throws IOException { 
     int c; 
     do { 
      c = super.read(); 
     } while(c != -1 && (c == '\n' || c == '\r')); 
     return c; 
    } 
} 

Và đối với một số thử nghiệm cơ bản ...

import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 

import junit.framework.Assert; 

import org.junit.BeforeClass; 
import org.junit.Test; 

public class NoNewLineFileInputStreamTest { 

    private final static String txt = "testnl.txt"; 

    @BeforeClass 
    public static void genTestFile() throws IOException { 
     OutputStream os = new FileOutputStream(txt); 
     os.write((
       "Hello\n" + 
       ",\r\n" + 
       "World!\r" + 
       "").getBytes()); 
     os.close(); 
    } 

    @Test 
    public void readInt() throws IOException { 
     InputStream is = new NoNewLineFileInputStream(txt); 
     int c = is.read(); 
     while(c != -1) { 
      Assert.assertTrue(c != '\n' && c != '\r'); 
      c = is.read(); 
     } 
     is.close(); 
    } 

    @Test 
    public void readBytes() throws IOException { 
     InputStream is = new NoNewLineFileInputStream(txt); 
     int l = is.available(); 
     if(l > 0) { 
      byte[] content = new byte[l]; 
      int n = is.read(content); 
      String expected = "Hello,World!"; 
      Assert.assertEquals(expected.getBytes().length, n); 
      Assert.assertEquals(expected, new String(content, 0, n)); 
     } 
     is.close(); 
    } 

    @Test 
    public void readBytesOffset() throws IOException { 
     InputStream is = new NoNewLineFileInputStream(txt); 
     int l = is.available(); 
     if(l > 0) { 
      byte[] content = new byte[l*3]; 
      int n = is.read(content, 3, 5); 
      String expected = "Hello"; 
      Assert.assertEquals(expected.getBytes().length, n); 
      Assert.assertEquals(expected, new String(content, 3, n)); 
     } 
     is.close(); 
    } 
} 

phương pháp của bạn sẽ trông như thế này

/** 
* @param target {@linkplain File} 
* @return {@linkplain InputStream} 
* @throws Exception 
*/ 
protected InputStream initInput(final File file) 
    throws Exception { 
    InputStream stream = null; 
    try { 
     if (file.isDirectory()) { 
      // throw exception 
     } 
     if (!file.exists()) { 
      // throw another exception 
     } 
     // 
     // read operations using this implementation will jump over all '\n' and '\r' 
     // 
     stream = new NoNewLineFileInputStream(file); 

    } catch (FileNotFoundException e) { 
     // throw another exception 
    } 
    return stream; 
} 

Đối khả năng tương thích tốt hơn với lớp trừu tượng java.io.InputStream mà bạn có thể muốn ghi đè tất cả các phương pháp của nó trong lớp học của bạn.

4

Bạn có thể chuyển nó sang một string, và thay thế các ký tự dòng mới với không có gì:

InputStream is = new ByteArrayInputStream("file content".getBytes()); 

    //read it with BufferedReader 
    BufferedReader br = new BufferedReader(new InputStreamReader(is)); 

    StringBuilder sb = new StringBuilder(); 

    String line; 
    while ((line = br.readLine()) != null) { 
     sb.append(line.replace("\r","").replace("\n",""))  


    System.out.println(sb.toString()); 

Điều này sẽ được xem xét tốt nếu văn bản của bạn không chứa "\ n" và "\ r" là relavent cho bạn.

Các vấn đề liên quan