package de.tutorials;
import java.io.FileDescriptor;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.Writer;
import java.lang.reflect.Field;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class FileWriterExample {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
FileWriter writer = new FileWriter("/home/tom/Desktop/spring-framework-3.0.0.M1-with-docs.zip");
String filePath = getPathOfFileUsedBy(writer);
System.out.println(filePath);
TimeUnit.SECONDS.sleep(300);
writer.close();
}
private static String getPathOfFileUsedBy(FileWriter writer) throws Exception {
String filePath = null;
ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo $PPID");
Process currentProcessIdDetectionProcess = processBuilder.start();
Scanner currentProcessIdDetectionProcessOutputScanner = new Scanner(currentProcessIdDetectionProcess.getInputStream());
while (currentProcessIdDetectionProcessOutputScanner.hasNextLine()) {
String currentProcessId = currentProcessIdDetectionProcessOutputScanner.nextLine().trim();
//System.out.println("PID: " + pid);
FileOutputStream fos = getValue("lock", writer, Writer.class);
int fd = getValue("fd", fos.getFD(), FileDescriptor.class);
//System.out.println("FD: " + fd);
processBuilder = new ProcessBuilder("/bin/sh", "-c", "lsof -p " + currentProcessId);
Process lsofProcess = processBuilder.start();
Scanner lsofProcessScanner = new Scanner(lsofProcess.getInputStream());
while (lsofProcessScanner.hasNextLine()) {
String line = lsofProcessScanner.nextLine();
String[] tokens = line.replaceAll("\\s+"," ").split(" ");
if (tokens[3].matches(fd +"\\w?")) {
filePath = tokens[8];
break;
}
}
lsofProcessScanner.close();
lsofProcess.waitFor();
}
currentProcessIdDetectionProcess.waitFor();
return filePath;
}
private static <T> T getValue(String fieldName, Object instance, Class<?> clazz) {
try {
Field field = clazz.getDeclaredField(fieldName);
field.setAccessible(true);
return (T) field.get(instance);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}