|
|
|
|
Here's an example of how you might write a filter stream
-- here, a
Note that I extended this class from When this program is applied to its own source, it outputs the following: package inputOutput;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.PushbackReader;
import java.io.Reader;
public class CommentFilterReader extends PushbackReader
{
public CommentFilterReader(Reader in)
{
super(in);
}
public int read()
throws IOException
{
int c = readNextNonCommentChar();
return c;
}
private int readNextNonCommentChar()
throws IOException
{
int c = super.read();
if (c == '/')
{
int lookAheadChar = super.read();
switch (lookAheadChar)
{
case '*':
while (true)
{
c = super.read();
if (c == -1)
break;
if (c == '*')
{
lookAheadChar = super.read();
if (lookAheadChar == '/')
{
c = ' ';
break;
}
}
}
break;
case '/':
while (true)
{
c = super.read();
if (c == -1)
break;
if (c == '\n')
{
break;
}
}
break;
default:
unread(lookAheadChar);
break;
}
}
return c;
}
public int read(char[] cbuf, int off, int len)
throws IOException
{
int count = 0;
for (int avail = cbuf.length - off;
len > 0 && avail > 0;
len--, avail--)
{
int c = readNextNonCommentChar();
if (c == -1)
{
if (count == 0)
count = -1;
break;
}
cbuf[off++] = (char)c;
count++;
}
return count;
}
public long skip(long n)
throws IOException
{
long count = 0;
for (count = 0; count < n; count++)
{
int c = readNextNonCommentChar();
if (c == -1)
break;
}
return count;
}
public static void main(String[] args)
{
try
{
BufferedReader reader = new BufferedReader(
new CommentFilterReader(
new FileReader(
args[0])));
PrintWriter writer = null;
if (args.length > 1)
{
writer = new PrintWriter(
new BufferedWriter(
new FileWriter(args[1])));
}
else
{
writer = new PrintWriter(
new OutputStreamWriter(
System.out));
}
while (true)
{
String line = reader.readLine();
if (line == null)
break;
writer.println(line);
}
reader.close();
writer.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
|
| The page was last updated February 19, 2008 |