I am using JUL in my application. Normally, Netbeans opens an output tab that reads "Tomcat" and shows the logs I produce. It was working fine. But suddenly, I realise that my logs are not shown at all, only the System.out get printed. Not even the higuest LOG.log(Level.SEVERE, ".....
} catch(Exception e) {
System.out.println("This gets printed in Netbeans tab");
LOG.log(Level.SEVERE, "This doesnt");
}
I suspect it can be a library I included, which is messing with my logs. Is that possible at all? Can a librray change the way my logs are shown? How can I investigate this, since I am a bit lost?
I suspect it can be a library I included, which is messing with my logs. Is that possible at all?
Yes. The JUL to SLF4J Bridge can remove the console handler from the JUL root logger. Some libraries invoke LogManager.reset which can remove and close all handlers.
Can a library change the way my logs are shown?
Yes. Once the a log bridge is installed the JUL records are no longer formatted by the JUL formatters.
How can I investigate this, since I am a bit lost?
Modifying the logger tree requires permissions so you can install a SecurityManager with all permissions but then turn on debug tracing with -Djava.security.debug="access,stack" to determine the caller that is modifying the logger tree.
If that doesn't work you can use good ole' System.out to print the logger tree and the attached handlers before and after a library is loaded. Then start adding an removing libraries until you see the logger change.
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.Logger;
public class DebugLogging {
private static final Logger log = Logger.getLogger("test");
public static void main(String[] a) {
log.log(Level.FINEST, "Finest");
log.log(Level.FINER, "FINER");
log.log(Level.FINE, "FINE");
log.log(Level.CONFIG, "CONFIG");
log.log(Level.INFO, "INFO");
log.log(Level.WARNING, "WARNING");
log.log(Level.SEVERE, "SEVERE");
log.finest("Finest Log");
log.finer("Finer Log");
log.fine("Fine Log");
log.config("Config Log");
log.info("Info Log");
log.warning("Warning Log");
log.severe("Severe Log");
printConfig(System.err);
}
private static void printConfig(PrintStream ps) {
String cname = System.getProperty("java.util.logging.config.class");
if (cname != null) {
try {
ClassLoader sys = ClassLoader.getSystemClassLoader();
Class<?> c = Class.forName(cname, false, sys);
ps.println(sys.getClass().getName() +" found log configuration class " + c.getName());
} catch (LinkageError | ClassNotFoundException | RuntimeException cnfe) {
ps.println("Unable to load " + cname);
cnfe.printStackTrace(ps);
}
} else {
ps.println("java.util.logging.config.class was null");
}
String file = System.getProperty("java.util.logging.config.file");
if (file != null) {
ps.println("java.util.logging.config.file=" + file);
try {
ps.println("CanonicalPath=" + new File(file).getCanonicalPath());
} catch (RuntimeException | IOException ioe) {
ps.println("Unable to resolve path for " + file);
ioe.printStackTrace(ps);
}
try {
Path p = Paths.get(file);
if (Files.isReadable(p)) {
ps.println(file + " is readable and has size " + Files.size(p));
} else {
if (Files.exists(p)) {
ps.println(file + " exists for " + System.getProperty("user.name") + " but is not readable.");
} else {
ps.println(file + " doesn't exist for " + System.getProperty("user.name"));
}
}
} catch (RuntimeException | IOException ioe) {
ps.println("Unable to read " + file);
ioe.printStackTrace(ps);
}
} else {
ps.println("java.util.logging.config.file was null");
}
LogManager lm = LogManager.getLogManager();
ps.append("LogManager=").println(lm.getClass().getName());
synchronized (lm) {
Enumeration<String> e = lm.getLoggerNames();
while (e.hasMoreElements()) {
Logger l = lm.getLogger(e.nextElement());
if (l != null) {
print(l, ps);
}
}
}
}
private static void print(Logger l, PrintStream ps) {
String scn = l.getClass().getSimpleName();
ps.append("scn=").append(scn).append(", n=").append(l.getName())
.append(", uph=").append(String.valueOf(l.getUseParentHandlers()))
.append(", l=").append(String.valueOf(l.getLevel()))
.append(", fl=").println(l.getFilter());
for (Handler h : l.getHandlers()) {
ps.append("\t").append(l.getName()).append("->")
.append(h.getClass().getName()).append(", h=")
.append(String.valueOf(h.getLevel())).append(", fl=")
.append(String.valueOf(h.getFilter())).println();
}
}
}
Related
I am using java.util.logging library for logging.
My code is as follows :
package com.test.vesrionControlSystem.services;
import java.io.IOException;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Formatter;
import java.util.logging.LogRecord;
import java.util.logging.Logger;
public class TestMain {
public static void main(String[] args) throws IOException, InterruptedException {
// TODO Auto-generated method stub
Logger logger = Logger.getLogger(TestMain.class.getName());
Logger logger1= Logger.getLogger(TestMain.class.getName());
FileHandler fh = new FileHandler("D:\\Logs\\FirstLogs.%g.log", 10000, 20, true);
FileHandler fh1 = new FileHandler("F:\\Logs\\SecondLogs.%g.log", 10000, 20, true);
fh.setFormatter(new Formatter() {
#Override
public String format(LogRecord record) {
return new Date(record.getMillis()) + " " + record.getLevel() + ": " + record.getMessage() + "\n";
}
});
fh1.setFormatter(new Formatter() {
#Override
public String format(LogRecord record) {
return new Date(record.getMillis()) + " " + record.getLevel() + ": " + record.getMessage() + "\n";
}
});
logger.addHandler(fh);
logger1.addHandler(fh1);
while(true) {
logger.info("printing info");
Thread.sleep(100);
logger1.warning("printing warning");
Thread.sleep(100);
logger.severe("Printing error");
Thread.sleep(100);
}
}
}
Here infos and severe messages should print in firstLogs.log file where as warning messages should be printed in secondsLogs.log file.
But I see all three messages (info, warning and severe) in both the files.
Please help me understand what I am missing here.
The main issue is that both logger and logger1 are the same name in your test code. Change the names:
Logger logger = Logger.getLogger(TestMain.class.getName() + ".0");
Logger logger1= Logger.getLogger(TestMain.class.getName() + ".1");
If you want to filter with in the same logger then see Logging handler usage
Its similar to one I answered recently but it was for log4j. please check it out How create diferents log File with different content using log4 in java configuration
I'm new in Hadoop! How can I run some hdfs commands from Java code? I've been testing successfully mapreduce with java code and hdfs commands directly from cloudera vm's terminal but now I'd like to learn how to do it with java code.
I've been looking for any materials where to learn but I haven't found yet.
Thanks
I think this may be help to you
I use it execute shell command well .here is the java example
public class JavaRunShell {
public static void main(String[] args){
try {
String shpath=" your command";
Process ps = Runtime.getRuntime().exec(shpath);
ps.waitFor();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
As mentioned by Jagrut, you can use FileSystem API in your java code to interact with hdfs command. Below is the sample code where i am trying to check if a particular directory exists in hdfs or not. If exists, then remove that hdfs directory.
Configuration conf = new Configuration();
Job job = new Job(conf,"HDFS Connect");
FileSystem fs = FileSystem.get(conf);
Path outputPath = new Path("/user/cloudera/hdfsPath");
if(fs.exists(outputPath))
fs.delete(outputPath);
You can also refer to given blogs for further reference -
https://dzone.com/articles/working-with-the-hadoop-file-system-api, https://hadoop.apache.org/docs/r2.8.2/api/org/apache/hadoop/fs/FileSystem.html
https://blog.knoldus.com/2017/04/16/working-with-hadoop-filesystem-api/
You can use the FileSystem API in your Java code to interact with HDFS.
You can use FileSystem API in java code to perform Hdfs commands.
https://hadoop.apache.org/docs/r2.8.2/api/org/apache/hadoop/fs/FileSystem.html
Please find the following sample code.
package com.hadoop.FilesystemClasses;
import java.io.IOException;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.Logger;
import com.hadoop.Constants.Constants;
public class HdfsFileSystemTasks {
public static Logger logger = Logger.getLogger(HdfsFileSystemTasks.class
.getName());
public FileSystem configureFilesystem(String coreSitePath,
String hdfsSitePath) {
FileSystem fileSystem = null;
try {
Configuration conf = new Configuration();
Path hdfsCoreSitePath = new Path(coreSitePath);
Path hdfsHDFSSitePath = new Path(hdfsSitePath);
conf.addResource(hdfsCoreSitePath);
conf.addResource(hdfsHDFSSitePath);
fileSystem = FileSystem.get(conf);
return fileSystem;
} catch (Exception ex) {
ex.printStackTrace();
return fileSystem;
}
}
public String writeToHDFS(FileSystem fileSystem, String sourcePath,
String destinationPath) {
try {
Path inputPath = new Path(sourcePath);
Path outputPath = new Path(destinationPath);
fileSystem.copyFromLocalFile(inputPath, outputPath);
return Constants.SUCCESS;
} catch (IOException ex) {
ex.printStackTrace();
return Constants.FAILURE;
}
}
public String readFileFromHdfs(FileSystem fileSystem, String hdfsStorePath,
String localSystemPath) {
try {
Path hdfsPath = new Path(hdfsStorePath);
Path localPath = new Path(localSystemPath);
fileSystem.copyToLocalFile(hdfsPath, localPath);
return Constants.SUCCESS;
} catch (IOException ex) {
ex.printStackTrace();
return Constants.FAILURE;
}
}
public String deleteHdfsDirectory(FileSystem fileSystem,
String hdfsStorePath) {
try {
Path hdfsPath = new Path(hdfsStorePath);
if (fileSystem.exists(hdfsPath)) {
fileSystem.delete(hdfsPath);
logger.info("Directory{} Deleted Successfully "
+ hdfsPath);
} else {
logger.info("Input Directory{} does not Exists " + hdfsPath);
}
return Constants.SUCCESS;
} catch (Exception ex) {
System.out
.println("Some exception occurred while reading file from hdfs");
ex.printStackTrace();
return Constants.FAILURE;
}
}
public String deleteLocalDirectory(FileSystem fileSystem,
String localStorePath) {
try {
Path localPath = new Path(localStorePath);
if (fileSystem.exists(localPath)) {
fileSystem.delete(localPath);
logger.info("Input Directory{} Deleted Successfully "
+ localPath);
} else {
logger.info("Input Directory{} does not Exists " + localPath);
}
return Constants.SUCCESS;
} catch (Exception ex) {
System.out
.println("Some exception occurred while reading file from hdfs");
ex.printStackTrace();
return Constants.FAILURE;
}
}
public void closeFileSystem(FileSystem fileSystem) {
try {
fileSystem.close();
} catch (Exception ex) {
ex.printStackTrace();
System.out.println("Unable to close Hadoop filesystem : " + ex);
}
}
}
package com.hadoop.FileSystemTasks;
import com.hadoop.Constants.HDFSParameters;
import com.hadoop.Constants.HdfsFilesConstants;
import com.hadoop.Constants.LocalFilesConstants;
import com.hadoop.FilesystemClasses.HdfsFileSystemTasks;
import org.apache.hadoop.fs.FileSystem;
import org.apache.log4j.Logger;
public class ExecuteFileSystemTasks {
public static Logger logger = Logger.getLogger(ExecuteFileSystemTasks.class
.getName());
public static void main(String[] args) {
HdfsFileSystemTasks hdfsFileSystemTasks = new HdfsFileSystemTasks();
FileSystem fileSystem = hdfsFileSystemTasks.configureFilesystem(
HDFSParameters.CORE_SITE_XML_PATH,
HDFSParameters.HDFS_SITE_XML_PATH);
logger.info("File System Object {} " + fileSystem);
String fileWriteStatus = hdfsFileSystemTasks.writeToHDFS(fileSystem,
LocalFilesConstants.SALES_DATA_LOCAL_PATH,
HdfsFilesConstants.HDFS_SOURCE_DATA_PATH);
logger.info("File Write Status{} " + fileWriteStatus);
String filereadStatus = hdfsFileSystemTasks.readFileFromHdfs(
fileSystem, HdfsFilesConstants.HDFS_DESTINATION_DATA_PATH
+ "/MR_Job_Res2/part-r-00000",
LocalFilesConstants.MR_RESULTS_LOCALL_PATH);
logger.info("File Read Status{} " + filereadStatus);
String deleteDirStatus = hdfsFileSystemTasks.deleteHdfsDirectory(
fileSystem, HdfsFilesConstants.HDFS_DESTINATION_DATA_PATH
+ "/MR_Job_Res2");
hdfsFileSystemTasks.closeFileSystem(fileSystem);
}
}
#HbnKing I tried running your code but I kept getting errors. This is the error i got
java.io.IOException: Cannot run program "your": CreateProcess error=2, The system cannot
find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknowenter code heren Source)
at jrs.main(jrs.java:5)
I want enable logging in classes JarClassLoader and Menu.
In Menu class it works (log is printed to file and console). But logging doesn't work in JarClassLoader (logging does not work either in the console or in the file).
For simplicity, I added the message only to the class constructor of JarClassLoader and one message at the beginning of main(String[] args) method.
log4j2.properties
name=PropertiesConfig
property.filename=classloading/menu-module/logs
appenders=console, file
appender.console.type=Console
appender.console.name=STDOUT
appender.console.layout.type=PatternLayout
appender.console.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
appender.file.type=File
appender.file.name=LOGFILE
appender.file.fileName=${filename}/propertieslogs.log
appender.file.layout.type=PatternLayout
appender.file.layout.pattern=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n
rootLogger.level=info
rootLogger.appenderRefs=stdout
rootLogger.appenderRef.stdout.ref=STDOUT
loggers=file
logger.file.name=com.example.classloading
logger.file.level=info
logger.file.appenderRefs=file
logger.file.appenderRef.file.ref=LOGFILE
JarClassLoader
package com.example.classloading;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class JarClassLoader extends ClassLoader {
private static final Logger log = LogManager.getLogger(JarClassLoader.class);
private HashMap<String, Class<?>> cache = new HashMap<String, Class<?>>();
private String jarFileName;
private String packageName;
private static String WARNING = "Warning : No jar file found. Packet unmarshalling won't be possible. Please verify your classpath";
public JarClassLoader(String jarFileName, String packageName) {
log.info(">> inside JarClassLoader");
this.jarFileName = jarFileName;
this.packageName = packageName;
cacheClasses();
}
private void cacheClasses() {
try {
JarFile jarFile = new JarFile(jarFileName);
Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry jarEntry = (JarEntry) entries.nextElement();
// simple class validation based on package name
if (match(normalize(jarEntry.getName()), packageName)) {
byte[] classData = loadClassData(jarFile, jarEntry);
if (classData != null) {
Class<?> clazz = defineClass(stripClassName(normalize(jarEntry.getName())), classData, 0, classData.length);
cache.put(clazz.getName(), clazz);
System.out.println("== class " + clazz.getName() + " loaded in cache");
}
}
}
}
catch (IOException IOE) {
System.out.println(WARNING);
}
}
public synchronized Class<?> loadClass(String name) throws ClassNotFoundException {
Class<?> result = cache.get(name);
if (result == null)
result = cache.get(packageName + "." + name);
if (result == null)
result = super.findSystemClass(name);
System.out.println("== loadClass(" + name + ")");
return result;
}
private String stripClassName(String className) {
return className.substring(0, className.length() - 6);
}
private String normalize(String className) {
return className.replace('/', '.');
}
private boolean match(String className, String packageName) {
return className.startsWith(packageName) && className.endsWith(".class");
}
private byte[] loadClassData(JarFile jarFile, JarEntry jarEntry) throws IOException {
long size = jarEntry.getSize();
if (size == -1 || size == 0)
return null;
byte[] data = new byte[(int)size];
InputStream in = jarFile.getInputStream(jarEntry);
in.read(data);
return data;
}
}
Menu
package com.example.classloading;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.Scanner;
public class Menu {
private static final Logger log = LogManager.getLogger();
public static void main(String[] args) {
int select;
do {
log.info(">> menu started");
System.out.println("=== MENU ===");
System.out.println("This is a simple multi-module project that can dynamically load modules.");
System.out.println("1. Load and run simple-module");
System.out.println("2. Load and run module in jar from ...");
System.out.println("0. EXIT");
Scanner scanner = new Scanner(System.in);
select = scanner.nextInt();
switch (select) {
case 1: {
JarClassLoader jarClassLoader = new JarClassLoader("classloading/simple-module/target/simple-module-1.0-SNAPSHOT.jar", "com.example.classloading");
try {
Class<?> clas = jarClassLoader.loadClass("com.example.classloading.SimpleModule");
Module sample = (Module) clas.newInstance();
sample.run();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
case 2: {
System.out.print(" Path to jar: ");
String jarFileName = scanner.next();
System.out.print(" Package name: ");
String packageName = scanner.next();
System.out.print(" Class to load and run: ");
String classToLoad = scanner.next();
JarClassLoader jarClassLoader = new JarClassLoader(jarFileName, packageName);
try {
Class<?> clas = jarClassLoader.loadClass(classToLoad);
Module sample = (Module) clas.newInstance();
sample.run();
} catch (Exception e) {
e.printStackTrace();
}
break;
}
}
} while (select != 0);
}
}
So, why does not logging work in the JarClassLoader class?
I have run your code and there is no problem with the logging. When I run the exact code, you have, the output is as follows;
[INFO ] 2017-04-09 20:07:15.208 [main] Menu - >> menu started
=== MENU ===
This is a simple multi-module project that can dynamically load modules.
1. Load and run simple-module
2. Load and run module in jar from ...
0. EXIT
1
[INFO ] 2017-04-09 20:07:20.681 [main] JarClassLoader - >> inside JarClassLoader
In your screenshot, I did not see that you have entered "1" or "2" in your console as the selection. As long as you do not enter anything from the console, the java program waits for an input and because of this reason, it never reaches to the line, in where logging is done.
I'm writing a plugin loader -- it loads jars that are not on the classpath. I wrote a simple custom ClassLoader that takes a JarFile in its constructor and looks in the JarFile for the named class. This loader simply overrides the findClass() method of ClassLoader, and works fine.
Then I determined that I also needed to be able to get resources from the plugin jar. So I overrode findResource(). This had the unexpected result of causing the base plugin class to not be able to find other classes in the jar: I get NoClassDefFoundErrors!
In other words, if I have plugin.jar that contains MyPlugin and MyPluginComponent:
if I do not override findResource(), then I can load the jar, create an instance of MyPlugin, and that in turn can create a MyPluginComponent. However I cannot find resources that are bundled in the jar.
if I do override findResource(), then I can load the jar, create an instance of MyPlugin, but if MyPlugin attempts to create a MyPluginComponent, I get a NoClassDefFoundError.
This suggests that somehow the implementation of findResource() is unable to find class files -- but it's not even getting called (per my logging), so I don't see how that could be the case. How does this interaction work out, and how do I fix it?
I tried to write a small self-contained example, and ran into difficulty manually generating a jar file that wouldn't produce "incompatible magic number" errors. Hopefully whatever I'm doing wrong will be evident from the class loader alone. Sorry for the inconvenience, and thank you for your time.
import com.google.common.io.CharStreams;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.lang.ClassLoader;
import java.net.URL;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
/**
* Custom class loader for loading plugin classes. Adapted from
* http://kalanir.blogspot.com/2010/01/how-to-write-custom-class-loader-to.html
*/
public static class PluginLoader extends ClassLoader {
private JarFile jarFile_;
public PluginLoader(JarFile jarFile) {
super(Thread.currentThread().getContextClassLoader());
jarFile_ = jarFile;
}
#Override
public Class findClass(String className) {
try {
// Replace "." with "/" for seeking through the jar.
String classPath = className.replace(".", "/") + ".class";
System.out.println("Searching for " + className + " under " + classPath);
JarEntry entry = jarFile_.getJarEntry(classPath);
if (entry == null) {
return null;
}
InputStream stream = jarFile_.getInputStream(entry);
String contents = CharStreams.toString(
new InputStreamReader(stream));
stream.close();
byte[] bytes = contents.getBytes();
Class result = defineClass(className, bytes, 0, bytes.length);
return result;
}
catch (IOException e) {
System.out.println(e + "Unable to load jar file " + jarFile_.getName());
}
catch (ClassFormatError e) {
System.out.println(e + "Unable to read class data for class " + className + " from jar " + jarFile_.getName());
}
return null;
}
#Override
protected URL findResource(String name) {
System.out.println("Asked to find resource at " + name);
try {
String base = new File(jarFile_.getName()).toURI().toURL().toString();
URL result = new URL(String.format("jar:%s!/%s", base, name));
System.out.println("Result is " + result);
return result;
}
catch (IOException e) {
System.out.println(e + "Unable to construct URL to find " + name);
return null;
}
}
#Override
public InputStream getResourceAsStream(String name) {
System.out.println("Getting resource at " +name);
JarEntry entry = jarFile_.getJarEntry(name);
if (entry == null) {
System.out.println("Couldn't find resource " + name);
return null;
}
try {
return jarFile_.getInputStream(entry);
}
catch (IOException e) {
System.out.println(e + "Unable to load resource " + name + " from jar file " + jarFile_.getName());
return null;
}
}
}
If your requirement is to just read extra JAR files extending URLClassLoader might be a better option.
public class PluginLoader extends URLClassLoader {
public PluginLoader(String jar) throws MalformedURLException {
super(new URL[] { new File(jar).toURI().toURL() });
}
}
So I have to make a program in java that automatically runs in the background and looks for a new .dat file and when it sees the new .dat file it then runs a .bat file to load data into a database. So far I have a program that watches for new file creation, modification, and deletion. I also have a script that runs the .bat file and loads the data into the database now i just need to connect the two but I am not sure how to go about this, If someone could point me in the right direction I would greatly appreciate it.
Below is the code I have so far.
import static java.nio.file.LinkOption.NOFOLLOW_LINKS;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import java.io.*;
import java.util.*;
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Order_Processing {
public static void watchDirectoryPath(Path path)
{
try {
Boolean isFolder = (Boolean) Files.getAttribute(path,
"basic:isDirectory", NOFOLLOW_LINKS);
if (!isFolder)
{
throw new IllegalArgumentException("Path: " + path
+ " is not a folder");
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
System.out.println("Watching path: "+ path);
FileSystem fs = path.getFileSystem();
try (WatchService service = fs.newWatchService())
{
path.register(service, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
WatchKey key = null;
while (true)
{
key = service.take();
Kind<?> kind = null;
for (WatchEvent<?> watchEvent : key.pollEvents())
{
kind = watchEvent.kind();
if (OVERFLOW == kind)
{
continue;
}
else if (ENTRY_CREATE == kind)
{
Path newPath = ((WatchEvent<Path>) watchEvent)
.context();
System.out.println("New Path Created: " + newPath);
}
else if (ENTRY_MODIFY == kind)
{
Path newPath = ((WatchEvent<Path>) watchEvent)
.context();
System.out.println("New path modified: "+ newPath);
}
else if (ENTRY_DELETE == kind)
{
Path newPath = ((WatchEvent<Path>) watchEvent)
.context();
System.out.println("New path deleted: "+ newPath);
}
}
if (!key.reset())
{
break;
}
}
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
catch (InterruptedException ie)
{
ie.printStackTrace();
}
}
public static void main(String[] args)
throws FileNotFoundException
{
File dir = new File("C:\\Paradigm");
watchDirectoryPath(dir.toPath());
//below is the script that runs the .bat file and it works if by itself
//with out all the other watch code.
try {
String[] command = {"cmd.exe", "/C", "Start", "C:\\Try.bat"};
Process p = Runtime.getRuntime().exec(command);
}
catch (IOException ex) {
}
}
}
This doesn't work because you have a while (true). This makes sense because you are listening and want the to happen continuously; however, the bat call will never be executed because watchDirectory(...) will never terminate. To solve this, pull the rest of the main out into its own function like so
public static void executeBat() {
try {
String[] command = {"cmd.exe", "/C", "Start", "C:\\Try.bat"};
Process p = Runtime.getRuntime().exec(command);
}
catch (IOException ex) {
// You should do something with this.
// DON'T JUST IGNORE FAILURES
}
so that upon file creation, you can call that bat script
...
else if (ENTRY_CREATE == kind)
{
Path newPath = ((WatchEvent<Path>) watchEvent).context();
executeBat();
}
...