简体   繁体   English

如何修改使用FileInputStream读取的文本文件的文本

[英]How to modify text of a text-file which is read using FileInputStream

I have to use a method whose signature is like this 我必须使用一种签名如下的方法

aMethod(FileInputStream);

I call that method like this 我这样叫那个方法

FileInputStream inputStream = new FileInputStream(someTextFile);
aMethod(inputStream);

I want to remove/edit some char which is being read from someTextFile before it being passed into aMethod(inputStream) ; 我想删除/编辑从someTextFile中读取的一些char,然后将其传递到aMethod(inputStream)

I cannot change aMethod's signature or overload it. 我无法更改aMethod的签名或使其重载。 And, it just take a InputStream. 而且,它只需要一个InputStream。 If method taking a string as param, then I wouldn't be asking this question. 如果方法采用字符串作为参数,那么我不会问这个问题。

I am InputStream noob. 我是InputStream菜鸟。 Please advise. 请指教。

you can convert a string into input stream 您可以将字符串转换为输入流

String str = "Converted stuff from reading the other inputfile and modifying it";
InputStream is = new ByteArrayInputStream(str.getBytes());

Here is something that might help. 这可能会有所帮助。 It will grab your .txt file. 它将获取您的.txt文件。 Then it will load it and go through line by line. 然后它将加载并逐行通过。 You have to fill in the commented areas to do what you want. 您必须填写评论区域才能执行所需的操作。

 public void parseFile() {
    String inputLine;
    String filename = "YOURFILE.txt";
    Thread thisThread = Thread.currentThread();
    ClassLoader loader = thisThread.getContextClassLoader();
    InputStream is = loader.getResourceAsStream(filename);
    try {
        FileWriter fstream = new FileWriter("path/to/NEWFILE.txt");
        BufferedWriter out = new BufferedWriter(fstream);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(is));
        while((inputLine = reader.readLine()) != null) {

            String[] str = inputLine.split("\t");
            if(/* IF WHAT YOU WANT IS IN THE FILE ADD IT */) {
                // DO SOMETHING OR ADD WHAT YOU WANT
                out.append(str);
                out.newLine();
            }
        }
        reader.close();
        out.close();
    } catch (Exception e) {
        e.getMessage();
    }
}

Have you looked at another class FilterInputStream which also extends InputStream which may fit into your requirement? 您是否看过另一个类FilterInputStream ,它也扩展了InputStream以满足您的需求? From the documentation for the class 从课程文档

A FilterInputStream contains some other input stream, which it uses as its basic source of data, possibly transforming the data along the way or providing additional functionality. FilterInputStream包含其他一些输入流,它用作其基本数据源,可能会沿途转换数据或提供其他功能。

Also have a look at this question which also seems to be similar to your question. 也看一下这个问题,它似乎也与您的问题相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM