How to find very large file copying status in java - java

I have requirement for monitoring the files copying status in a directory and the files are placed continuously into the directory in java.
I am planing to use Executor framework to find out individual files copy status and I have written below code but it is not working as expected, file without copy completion I am getting notification as copying got completed.
private boolean isFileCopied(String filePath) {
File file = new File(filePath);
Scanner scanner;
boolean isCopied = true;
while (true) {
try {
scanner = new Scanner(file);
isCopied = false;
} catch (FileNotFoundException e) {
System.out.println(filePath + " File is in copy State. ");
sleepFile();
}
if (isCopied == false) {
break;
}
}
System.out.println(filePath + " copy completed");
return isCopied;
}
private static void sleepFile() {
System.out.println("sleeping for 10 seconds");
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Please someone help me out how can I find the exact status of a file like file "copy in progress" or "copying done" and how can I monitor each and every file copying status If bunch of large files placed in a directory.
I have used watcher API but it is not solving my purpose. even the file without copying got completed I am getting notification as copying got completed. Below are my code changes.
Using watcher service:
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class FolderWatchDemo {
public static void main(String[] args) {
final Path outputWatchFolderPath = Paths.get("/outputFolder/");
final Path sourceFolderPath = Paths.get("/sourceFolder/");
try {
//Registering outputWatchFolderPath
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get(outputWatchFolderPath.toString());
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: " + dir.getFileName());
//copy files from inputfolder to o
for (final Path path: Files.newDirectoryStream(sourceFolderPath))
Files.copy(path, outputWatchFolderPath.resolve(path.getFileName()));
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
WatchEvent<Path> ev = (WatchEvent<Path>) event;
if (kind == ENTRY_CREATE) {
System.out.println("file got created !!");
}
if (kind == ENTRY_MODIFY) {
System.out.println("copying got completed !!");
}
if (kind == ENTRY_DELETE) {
System.out.println("file deleted successfully !!");
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Thanks in Advance.

There is a very elegant way to create a Call Back system and implementing it via implementing ReadableByteChannel in order to monitor the progerss of copying files. Also the benefit is there is no need to monitor a directory. You can explicitly monitor the progress of the file which is being copied.
The main idea is proposed by this site, but changed it a little to fit in your problem:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
interface ProgressCallBack {
public void callback(CallbackByteChannel rbc, double progress);
}
public class Main{
public static void main(String[] args) {
ProgressCallBack progressCallBack = new ProgressCallBack() {
#Override
public void callback(CallbackByteChannel rbc, double progress) {
System.out.println(rbc.getReadSoFar());
System.out.println(progress);
}
};
try {
copy("SOURCE FILE PATH", "DESTINATION FILE PATH", progressCallBack);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void copy(String source, String destination, ProgressCallBack callBack) throws IOException {
FileOutputStream fos = null;
FileChannel sourceChannel = null;
try {
sourceChannel = new FileInputStream(new File(source)).getChannel();
ReadableByteChannel rbc = new CallbackByteChannel(sourceChannel, Files.size(Paths.get(source)), callBack);
fos = new FileOutputStream(destination);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(sourceChannel.isOpen()){
sourceChannel.close();
}
fos.close();
}
}
}
class CallbackByteChannel implements ReadableByteChannel {
ProgressCallBack delegate;
long size;
ReadableByteChannel rbc;
long sizeRead;
CallbackByteChannel(ReadableByteChannel rbc, long expectedSize, ProgressCallBack delegate) {
this.delegate = delegate;
this.size = expectedSize;
this.rbc = rbc;
}
public void close() throws IOException {
rbc.close();
}
public long getReadSoFar() {
return sizeRead;
}
public boolean isOpen() {
return rbc.isOpen();
}
public int read(ByteBuffer bb) throws IOException {
int n;
double progress;
if ((n = rbc.read(bb)) > 0) {
sizeRead += n;
progress = size > 0 ? (double) sizeRead / (double) size * 100.0 : -1.0;
delegate.callback(this, progress);
}
return n;
}
}
Hope this help.

package test;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class FolderWatchDemo {
public static void main(String[] args) {
final Path outputWatchFolderPath = Paths.get("/outputFolder/");
final Path sourceFolderPath = Paths.get("/sourceFolder/");
try {
// Registering outputWatchFolderPath
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get(outputWatchFolderPath.toString());
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: " + dir.getFileName());
// copy files from inputfolder to o
for (final Path path : Files.newDirectoryStream(sourceFolderPath))
Files.copy(path, outputWatchFolderPath.resolve(path.getFileName()),
StandardCopyOption.REPLACE_EXISTING);
String fileName = null;
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
WatchEvent<Path> ev = (WatchEvent<Path>) event;
if (kind == ENTRY_CREATE) {
System.out.println("file got created !!" + ev.context());
}
if (kind == ENTRY_MODIFY) {
String fName = ev.context().getFileName().toString();
if (fileName != null && !fName.equals(fileName)) {
System.out.println("file copying completed !!" + fileName);
}
fileName = fName;
System.out.println("copying " + fName);
}
if (kind == ENTRY_DELETE) {
System.out.println("file deleted successfully !!");
}
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}

Related

How I can create TOC using apache poi

I have the code which create table of content like this:
image screenshot ,
but i want resualt like this:
image screenshot ,
and this is my code
package com.example;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.commons.compress.archivers.dump.InvalidFormatException;
import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSimpleField;
These are libraries which I'm using for this project
and I'm also using the maven package manager
public class toc {
public static void main(String[] args) throws IOException, OpenXML4JException {
XWPFDocument docTemplate = null;
try {
File file = new File(
"outfile02.docx"); // "C:\\Reports\\Template.docx";
FileInputStream fis = new FileInputStream(file);
docTemplate = new XWPFDocument(fis);
generateTOC(docTemplate);
saveDocument(docTemplate);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (docTemplate != null) {
docTemplate.close();
}
}
}
save function
private static void saveDocument(XWPFDocument docTemplate) throws FileNotFoundException, IOException {
FileOutputStream outputFile = null;
try {
outputFile = new FileOutputStream("outfile03.docx");
docTemplate.write(outputFile);
} finally {
if (outputFile != null) {
outputFile.close();
}
}
}
TOC generator function
public static void generateTOC(XWPFDocument document)
throws InvalidFormatException, FileNotFoundException, IOException {
String findText = "${TOC}";
String replaceText = "";
for (XWPFParagraph p : document.getParagraphs()) {
for (XWPFRun r : p.getRuns()) {
int pos = r.getTextPosition();
String text = r.getText(pos);
if (text != null && text.contains(findText)) {
text = text.replace(findText, replaceText);
r.setText(text, 0);
addField(p, "TOC \\o \"1-3\" \\h \\z \\u");
break;
}
}
}
}
and this is last function
private static void addField(XWPFParagraph paragraph, String fieldName) {
CTSimpleField ctSimpleField = paragraph.getCTP().addNewFldSimple();
// ctSimpleField.setInstr(fieldName + " \\h ");
ctSimpleField.setInstr(fieldName);
ctSimpleField.addNewR().addNewT().setStringValue("outfile03.docx");
}
}

How to unzip all the password protected zip files in a directory using Java

I am new to java and trying to write an program which will unzip all the password protected zip files in an directory, I am able to unzip all the normal zip files (Without password) but I am not sure how to unzip password protected files.
Note: All zip files have same password
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.PathMatcher;
import java.nio.file.Paths;
import java.util.List;
import java.util.stream.Stream;
import java.util.zip.ZipEntry;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
import java.util.zip.*;
public class Extraction {
// public Extraction() {
//
// try {
//
// ZipFile zipFile = new
// ZipFile("C:\\Users\\Desktop\\ZipFile\\myzip.zip");
//
// if (zipFile.isEncrypted()) {
//
// zipFile.setPassword("CLAIMS!");
// }
//
// List fileHeaderList = zipFile.getFileHeaders();
//
// for (int i = 0; i < fileHeaderList.size(); i++) {
// FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
//
// zipFile.extractFile(fileHeader, "C:\\Users\\Desktop\\ZipFile");
// System.out.println("Extracted");
// }
//
// } catch (Exception e) {
// System.out.println("Please Try Again");
// }
//
// }
//
// public static void main(String[] args) {
// new Extraction();
//
// }
// }
public static void main(String[] args) {
Extraction unzipper = new Extraction();
unzipper.unzipZipsInDirTo(Paths.get("C:\\Users\\Desktop\\ZipFile"),
Paths.get("C:\\Users\\Desktop\\ZipFile\\Unziped"));
}
public void unzipZipsInDirTo(Path searchDir, Path unzipTo) {
final PathMatcher matcher = searchDir.getFileSystem().getPathMatcher("glob:**/*.zip");
try (final Stream<Path> stream = Files.list(searchDir)) {
stream.filter(matcher::matches).forEach(zipFile -> unzip(zipFile, unzipTo));
} catch (Exception e) {
System.out.println("Something went wrong, Please try again!!");
}
}
public void unzip(Path zipFile, Path outputPath) {
try (ZipInputStream zis = new ZipInputStream(Files.newInputStream(zipFile))) {
ZipEntry entry = zis.getNextEntry();
while (entry != null) {
Path newFilePath = outputPath.resolve(entry.getName());
if (entry.isDirectory()) {
Files.createDirectories(newFilePath);
} else {
if (!Files.exists(newFilePath.getParent())) {
Files.createDirectories(newFilePath.getParent());
}
try (OutputStream bos = Files.newOutputStream(outputPath.resolve(newFilePath))) {
byte[] buffer = new byte[Math.toIntExact(entry.getSize())];
int location;
while ((location = zis.read(buffer)) != -1) {
bos.write(buffer, 0, location);
}
}
}
entry = zis.getNextEntry();
}
} catch (Exception e1) {
System.out.println("Please try again");
}
}
}
I found the answer I am posting this as there might be someone else who might be looking for the similar answer.
import java.io.File;
import java.util.List;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.FileHeader;
public class SamExtraction {
public static void main(String[] args) {
final FileNameExtensionFilter extensionFilter = new FileNameExtensionFilter("N/A", "zip");
//Folder where zip file is present
final File file = new File("C:/Users/Desktop/ZipFile");
for (final File child : file.listFiles()) {
try {
ZipFile zipFile = new ZipFile(child);
if (extensionFilter.accept(child)) {
if (zipFile.isEncrypted()) {
//Your ZIP password
zipFile.setPassword("MYPASS!");
}
List fileHeaderList = zipFile.getFileHeaders();
for (int i = 0; i < fileHeaderList.size(); i++) {
FileHeader fileHeader = (FileHeader) fileHeaderList.get(i);
//Path where you want to Extract
zipFile.extractFile(fileHeader, "C:/Users/Desktop/ZipFile");
System.out.println("Extracted");
}
}
} catch (Exception e) {
System.out.println("Please Try Again");
}
}
}
}

how to use At4J or 7-Zip-JBinding to get an InputStream of a file?

I looked into at4j and 7-Zip-JBinding (their javadoc and documentation) but they doesn't seem to be able to read without extracting (and get an InputStream from archived file)
Is there any method I'm missing or haven't found ?
a solution other than extracting to a temporary folder to read it
I'm expecting an answer in how to do it in at4j or 7-Zip-JBinding
in other words I want to know how to utilize below mentioned function in at4j or 7-Zip-JBinding
I know java's built in one has getInputStream I'm currently using it this way
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
/**
* get input stream of current file
* #param path path inside zip
* #return InputStream
*/
public InputStream getInputStream(String path){
try {
ZipEntry entry = zipFile.getEntry(path);
if(entry!=null){
return zipFile.getInputStream(entry);
}
return new ByteArrayInputStream("Not Found".getBytes());
} catch (Exception ex) {
//handle exception
}
return null;
}
(^^ zipFile is a ZipFile object)
found the solution using 7-Zip-JBinding
just need to use ByteArrayInputStream ,this so far worked for a small file
pass a archive as argument to get all files inside printed
file ExtractItemsSimple.java
import java.io.IOException;
import java.io.RandomAccessFile;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class ExtractItemsSimple {
public static void main(String[] args) {
RandomAccessFile randomAccessFile = null;
ISevenZipInArchive inArchive = null;
try {
randomAccessFile = new RandomAccessFile(args[0], "r");
inArchive = SevenZip.openInArchive(null, // autodetect archive type
new RandomAccessFileInStream(randomAccessFile));
ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();
for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
final int[] hash = new int[] { 0 };
if (!item.isFolder()) {
System.out.println(ArchieveInputStreamHandler.slurp(new ArchieveInputStreamHandler(item).getInputStream(),1000));
}
}
} catch (Exception e) {
System.err.println("Error occurs: " + e);
System.exit(1);
} finally {
if (inArchive != null) {
try {
inArchive.close();
} catch (SevenZipException e) {
System.err.println("Error closing archive: " + e);
}
}
if (randomAccessFile != null) {
try {
randomAccessFile.close();
} catch (IOException e) {
System.err.println("Error closing file: " + e);
}
}
}
}
}
file ArchieveInputStreamHandler.java
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
public class ArchieveInputStreamHandler {
private ISimpleInArchiveItem item;
private ByteArrayInputStream arrayInputStream;
public ArchieveInputStreamHandler(ISimpleInArchiveItem item) {
this.item = item;
}
public InputStream getInputStream() throws SevenZipException{
item.extractSlow(new ISequentialOutStream() {
#Override
public int write(byte[] data) throws SevenZipException {
arrayInputStream = new ByteArrayInputStream(data);
return data.length; // Return amount of consumed data
}
});
return arrayInputStream;
}
//got from http://stackoverflow.com/questions/309424/read-convert-an-inputstream-to-a-string
public static String slurp(final InputStream is, final int bufferSize){
final char[] buffer = new char[bufferSize];
final StringBuilder out = new StringBuilder();
try {
final Reader in = new InputStreamReader(is, "UTF-8");
try {
for (;;) {
int rsz = in.read(buffer, 0, buffer.length);
if (rsz < 0)
break;
out.append(buffer, 0, rsz);
}
}
finally {
in.close();
}
}
catch (UnsupportedEncodingException ex) {
/* ... */
}
catch (IOException ex) {
/* ... */
}
return out.toString();
}
}
Are you looking for http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipInputStream.html which can extract entries in zip file without extracting it completely.

Parse zip or Jar project

I need to return all the packages, classes ... that a java project (zip/jar) contains. I guess QDox can do that. I found that class : http://www.jarvana.com/jarvana/view/com/ning/metrics.serialization-all/2.0.0-pre5/metrics.serialization-all-2.0.0-pre5-jar-with-dependencies-sources.jar!/com/thoughtworks/qdox/tools/QDoxTester.java?format=ok
package com.thoughtworks.qdox.tools;
import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.directorywalker.DirectoryScanner;
import com.thoughtworks.qdox.directorywalker.FileVisitor;
import com.thoughtworks.qdox.directorywalker.SuffixFilter;
import com.thoughtworks.qdox.parser.ParseException;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Tool for testing that QDox can parse Java source code.
*
* #author Joe Walnes
*/
public class QDoxTester {
public static interface Reporter {
void success(String id);
void parseFailure(String id, int line, int column, String reason);
void error(String id, Throwable throwable);
}
private final Reporter reporter;
public QDoxTester(Reporter reporter) {
this.reporter = reporter;
}
public void checkZipOrJarFile(File file) throws IOException {
ZipFile zipFile = new ZipFile(file);
Enumeration entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) entries.nextElement();
InputStream inputStream = zipFile.getInputStream(zipEntry);
try {
verify(file.getName() + "!" + zipEntry.getName(), inputStream);
} finally {
inputStream.close();
}
}
}
public void checkDirectory(File dir) throws IOException {
DirectoryScanner directoryScanner = new DirectoryScanner(dir);
directoryScanner.addFilter(new SuffixFilter(".java"));
directoryScanner.scan(new FileVisitor() {
public void visitFile(File file) {
try {
checkJavaFile(file);
} catch (IOException e) {
// ?
}
}
});
}
public void checkJavaFile(File file) throws IOException {
InputStream inputStream = new FileInputStream(file);
try {
verify(file.getName(), inputStream);
} finally {
inputStream.close();
}
}
private void verify(String id, InputStream inputStream) {
try {
JavaDocBuilder javaDocBuilder = new JavaDocBuilder();
javaDocBuilder.addSource(new BufferedReader(new InputStreamReader(inputStream)));
reporter.success(id);
} catch (ParseException parseException) {
reporter.parseFailure(id, parseException.getLine(), parseException.getColumn(), parseException.getMessage());
} catch (Exception otherException) {
reporter.error(id, otherException);
}
}
public static void main(String[] args) throws IOException {
if (args.length == 0) {
System.err.println("Tool that verifies that QDox can parse some Java source.");
System.err.println();
System.err.println("Usage: java " + QDoxTester.class.getName() + " src1 [src2] [src3]...");
System.err.println();
System.err.println("Each src can be a single .java file, or a directory/zip/jar containing multiple source files");
System.exit(-1);
}
ConsoleReporter reporter = new ConsoleReporter(System.out);
QDoxTester qDoxTester = new QDoxTester(reporter);
for (int i = 0; i < args.length; i++) {
File file = new File(args[i]);
if (file.isDirectory()) {
qDoxTester.checkDirectory(file);
} else if (file.getName().endsWith(".java")) {
qDoxTester.checkJavaFile(file);
} else if (file.getName().endsWith(".jar") || file.getName().endsWith(".zip")) {
qDoxTester.checkZipOrJarFile(file);
} else {
System.err.println("Unknown input <" + file.getName() + ">. Should be zip, jar, java or directory");
}
}
reporter.writeSummary();
}
private static class ConsoleReporter implements Reporter {
private final PrintStream out;
private int success;
private int failure;
private int error;
private int dotsWrittenThisLine;
public ConsoleReporter(PrintStream out) {
this.out = out;
}
public void success(String id) {
success++;
if (++dotsWrittenThisLine > 80) {
newLine();
}
out.print('.');
}
private void newLine() {
dotsWrittenThisLine = 0;
out.println();
out.flush();
}
public void parseFailure(String id, int line, int column, String reason) {
newLine();
out.println("* " + id);
out.println(" [" + line + ":" + column + "] " + reason);
failure++;
}
public void error(String id, Throwable throwable) {
newLine();
out.println("* " + id);
throwable.printStackTrace(out);
error++;
}
public void writeSummary() {
newLine();
out.println("-- Summary --------------");
out.println("Success: " + success);
out.println("Failure: " + failure);
out.println("Error : " + error);
out.println("Total : " + (success + failure + error));
out.println("-------------------------");
}
}
}
It contains a method called checkZipOrJarFile(File file), maybe it could help me. but I can't find any examples or tutorials on how to use it.
Any help is welcomed.
QDox cannot do that for you, unfortunately (I came here looking for QDox support for jars). The source code for QDox that you list above is only for testing if the classes in the given jar can be parsed successfully by QDox. That code does, however, give you a clue on how to use standard java apis to do what you want: enumerate over classed in a jar.
Here's some code I'm using (which I cribbed from another SO answer here: analyze jar file programmatically)
// Your jar file
JarFile jar = new JarFile(jarFile);
// Getting the files into the jar
Enumeration<? extends JarEntry> enumeration = jar.entries();
// Iterates into the files in the jar file
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = enumeration.nextElement();
// Is this a class?
if (zipEntry.getName().endsWith(".class")) {
// Relative path of file into the jar.
String className = zipEntry.getName();
// Complete class name
className = className.replace(".class", "").replace("/", ".");
// Load class definition from JVM - you may not need this, but I want to introspect the class
try {
Class<?> clazz = getClass().getClassLoader().loadClass(className);
// ... I then go on to do some intropsection
If you don't actually want to introspect the class as I do, you can stop at getName(). Also, if you specifically want to find packages, you could use zipEntry.isDirectory() on your zip entries.

monitor multiple log file simultaneously

I have made a program that continuously monitors a log file. But I don't know how to monitor multiple log files. This is what I did to monitor single file. What changes should I make in the following code so that it monitors multiple files also?
package com.read;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class FileWatcherTest {
public static void main(String args[]) {
final File fileName = new File("D:/logs/myFile.log");
// monitor a single file
TimerTask fileWatcherTask = new FileWatcher(fileName) {
long addFileLen = fileName.length();
FileChannel channel;
FileLock lock;
String a = "";
String b = "";
#Override
protected void onChange(File file) {
RandomAccessFile access = null;
try {
access = new RandomAccessFile(file, "rw");
channel = access.getChannel();
lock = channel.lock();
if (file.length() < addFileLen) {
access.seek(file.length());
} else {
access.seek(addFileLen);
}
} catch (Exception e) {
e.printStackTrace();
}
String line = null;
try {
while ((line = access.readLine()) != null) {
System.out.println(line);
}
addFileLen = file.length();
} catch (IOException ex) {
Logger.getLogger(FileWatcherTest.class.getName()).log(
Level.SEVERE, null, ex);
}
try {
lock.release();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} // Close the file
try {
channel.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
Timer timer = new Timer();
// repeat the check every second
timer.schedule(fileWatcherTask, new Date(), 1000);
}
}
package com.read;
import java.util.*;
import java.io.*;
public abstract class FileWatcher extends TimerTask {
private long timeStamp;
private File file;
static String s;
public FileWatcher(File file) {
this.file = file;
this.timeStamp = file.lastModified();
}
public final void run() {
long timeStamp = file.lastModified();
if (this.timeStamp != timeStamp) {
this.timeStamp = timeStamp;
onChange(file);
}
}
protected abstract void onChange(File file);
}
You should use threads. Here's a good tutorial:
http://docs.oracle.com/javase/tutorial/essential/concurrency/
You would do something like:
public class FileWatcherTest {
public static void main(String args[]) {
(new Thread(new FileWatcherRunnable("first.log"))).start();
(new Thread(new FileWatcherRunnable("second.log"))).start();
}
private static class FileWatcherRunnable implements Runnable {
private String logFilePath;
// you should inject the file path of the log file to watch
public FileWatcherRunnable(String logFilePath) {
this.logFilePath = logFilePath;
}
public void run() {
// your code from main goes in here
}
}
}

Categories