Reputation: 119
I got InputStream
from URL but I need to replace or remove a string and write to file. I try to use extension of FilterInputStream
to replace, but my file is still the same.
I not necessarily need to have InputStream
-> InputStream.replace()
but InputStream
-> File
with string replace
class ReplacingInputStream extends FilterInputStream {
LinkedList<Integer> inQueue = new LinkedList<Integer>();
LinkedList<Integer> outQueue = new LinkedList<Integer>();
final byte[] search, replacement;
protected ReplacingInputStream(InputStream in,
byte[] search,
byte[] replacement) {
super(in);
this.search = search;
this.replacement = replacement;
}
private boolean isMatchFound() {
Iterator<Integer> inIter = inQueue.iterator();
for (int i = 0; i < search.length; i++)
if (!inIter.hasNext() || search[i] != inIter.next())
return false;
return true;
}
private void readAhead() throws IOException {
// Work up some look-ahead.
while (inQueue.size() < search.length) {
int next = super.read();
inQueue.offer(next);
if (next == -1)
break;
}
}
@Override
public int read() throws IOException {
// Next byte already determined.
if (outQueue.isEmpty()) {
readAhead();
if (isMatchFound()) {
for (int i = 0; i < search.length; i++)
inQueue.remove();
for (byte b : replacement)
outQueue.offer((int) b);
} else
outQueue.add(inQueue.remove());
}
return outQueue.remove();
}
}
InputStream is = connection.getInputStream();
byte[] search = "\"https\"".getBytes("UTF-8");
byte[] replacement = "".getBytes("UTF-8");
InputStream ris = new ReplacingInputStream(is, search, replacement);
Files.copy(ris, file.toPath(), StandardCopyOption.REPLACE_EXISTING);
Upvotes: 1
Views: 666
Reputation: 119
Finally i use scanner
InputStream is = connection.getInputStream();
String search = "\"https\"";
String replace = "";
try(Scanner scanner = new Scanner(is);
BufferedWriter writer = new BufferedWriter(new FileWriter(file))) {
while(scanner.hasNextLine()){
writer.append(scanner.nextLine().replace(search,replace));
writer.newLine();
}
}
Upvotes: 1