Write your own Progress Listener
While writing some other articles over Anonymous Classes, I wrote a code to watch over how many bytes of a file has bean read or write. I am sharing that code with all of you to improve understanding in use of anonymous Classes, advanced java concept.
This is very simple and handy code. You can change it as per your need like to keep a watch over file uploading (to limit upload file size), or intimating admin via mail when log file size exceed etc.
This article will also help you to understand need of interfaces over abstract classes.
myFileWriter.java
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
/**
* Copyright (C) 2011 Amit Gupta
* You are free to redistribute the code or its modified version
* by giving the credit to original code.
*
* This code is useful to understand the concept and
* importance of anonymous class. And how to reuse java classes
* @author Amty
*
*/
public class myFileWriter extends OutputStreamWriter //implements myProgressListener
{
myProgressListener mpl;
long pBytesWrite;
public myFileWriter(OutputStream arg0) {
super(arg0);
//mpl=this;
pBytesWrite=0;
}
@Override
public void write(int c) throws IOException {
super.write(c);
pBytesWrite++;
if(mpl != null){
mpl.update(pBytesWrite);
}
}
public void setProgressListener(myProgressListener mpl){
this.mpl = mpl;
}
//public void update(long pBytesRead, long pContentLength, int pItems){}
public static void main(String[] args) throws Exception{
FileOutputStream fos = new FileOutputStream("D:\\article-stack\\amtyOutput.txt");
FileInputStream fis = new FileInputStream("D:\\article-stack\\amtyInput.txt");
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
Reader in = new BufferedReader(isr);
myProgressListener mpltest = new myProgressListener() {
@Override
public void update(long pBytesWrite) {
System.out.println(pBytesWrite + "Bytes are written");
}
};
myFileWriter mfw = new myFileWriter(fos);
mfw.setProgressListener(mpltest);
int ch;
while ((ch = in.read()) > -1) {
mfw.write((char) ch);
}
in.close();
mfw.close();
}
}
myProgressListener.java
public interface myProgressListener {
public void update(long pBytesWrite);
}
Output:
74381Bytes are written 74382Bytes are written 74383Bytes are written : 77710Bytes are written 77711Bytes are written 77712Bytes are written 77713Bytes are written 77714Bytes are written
Here is attached code for your reference.
This area is protected to registered users only.




































































