从InputStream中删除换行符 [英] Removing newline characters from InputStream

查看:185
本文介绍了从InputStream中删除换行符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在读取文件的同时从 java.io.InputStream 中删除​​所有换行符(对于\ n和\\\\ n)相应的方法如下所示:

I like to remove all newline characters (for both \n and \r\n) from an java.io.InputStream, while reading a file, the corresponding method looks like this:

/**
 * @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;
}


推荐答案

你可以拥有自己的实力 java.io.FileInputStream 并以跳过 \ r 和<的方式覆盖读取方法读取时code> \ n 。

You could have your own implmentation of java.io.FileInputStream and Override the read-methods in a way that you jump over \r and \n while reading.

Hier是示例实现(没有任何错误处理)

Hier is sample Implementation (without any error handling)

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;
    }
}

并进行一些基本测试......

And for some basic testing ...

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();
    }
}

您的方法看起来像这样

/**
 * @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;
}

为了更好地兼容 java.io.InputStream 抽象类,您可能希望覆盖类中的所有方法。

For better compatibility with the java.io.InputStream abstract class you may want to override all its methods in your class.

这篇关于从InputStream中删除换行符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆