0

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

I cannot change aMethod's signature or overload it. And, it just take a InputStream. If method taking a string as param, then I wouldn't be asking this question.

I am InputStream noob. Please advise.

Watt
  • 3,118
  • 14
  • 54
  • 85

3 Answers3

2

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());
Techmonk
  • 1,459
  • 12
  • 20
1

Here is something that might help. It will grab your .txt file. 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();
    }
}
Jane Doh
  • 2,883
  • 3
  • 15
  • 17
  • no need to create a new file directly convert string into inputstream – Techmonk Feb 05 '13 at 16:52
  • But he wants to remove certain characters from the initial file before it is read in. – Jane Doh Feb 05 '13 at 16:54
  • I imagine he does not want to edit the file; just modify the input before feeding it to the aMethod() – Techmonk Feb 05 '13 at 16:56
  • Techmonk, you got it right. Sorry Jane, if question was little bit confusing. Thanks both of you for great answers. I will come back to accept answer once I test it. – Watt Feb 05 '13 at 16:58
1

Have you looked at another class FilterInputStream which also extends InputStream which may fit into your requirement? 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.

Also have a look at this question which also seems to be similar to your question.

Community
  • 1
  • 1
Shiva Kumar
  • 3,111
  • 1
  • 26
  • 34