java.lang.IllegalArgumentException: File Not found - java

I am trying to read an Ontology using Jena. I have a file Pizza.owl in the correct directory shown in the code, but I still get an error that the file is not found.
public static void ReadOntology(){
OntModel onto = ModelFactory.createOntologyModel(OntModelSpec.OWL_MEM, null);
String inputFileName = "C:\\Users\\najib\\studies\\pizza.owl";
try {
Logger logger = Logger.getLogger(Operations.class);
PropertyConfigurator.configure("C://Users//najib//Downloads//apache-jena-2.12.0//jena-log4j.properties");
//create the reasoning model using the base
OntModel model = ModelFactory.createOntologyModel();
// use the FileManager to find the input file
InputStream in = FileManager.get().open(inputFileName);
if (in == null) {
throw new IllegalArgumentException("File: " + inputFileName + " not found");
}
model.read(in, "");
//to list classes
ExtendedIterator<OntClass> classes = model.listClasses();
while (classes.hasNext()) {
OntClass cls = (OntClass) classes.next();
System.out.println("Classes: " + cls.getLocalName());
for (ExtendedIterator<OntClass> i = cls.listSubClasses(true); i.hasNext();) {
OntClass c = (OntClass) i.next();
System.out.print(" " + c.getLocalName() + "\n");
} // end for
}
} catch (Exception e) {
System.out.println(e);
}
}
}
I get the following error: java.lang.IllegalArgumentException: File: C:\Users\najib\studies\pizza.owl not found

When I read the javadoc of FileManager, I see you have to prefix your file parameter with "file:"
So (without testing this answer) I suggest to try it with:
String inputFileName = "file:/C:/Users/najib/studies/pizza.owl";

Related

Java PrintStream .println() method not outputting to file?

I am trying to write a method which recursively gathers data from files, and writes erroneous data to an error file. See code block:
public static LinkedQueue<Stock> getStockData(LinkedQueue<Stock> stockQueue, String startPath) throws Exception {
File dir = new File(getValidDirectory(startPath));
try (PrintStream recordErrors = new PrintStream(new File("EODdataERRORS.txt"))) {
for (File name : dir.listFiles()) {
if (name.isDirectory()) {
getStockData(stockQueue, name.getPath());
}
else if (name.canRead()) {
Scanner readFile = new Scanner(name);
readFile.nextLine();
while (readFile.hasNext()) {
String line = readFile.nextLine();
String[] lineArray = line.split(",+");
if (lineArray.length == 8) {
try {
Stock stock = new Stock(name.getName().replaceAll("_+(.*)", ""));
stock.fromRecord(lineArray);
stockQueue.enqueue(stock);
}
catch (Exception ex) {
recordErrors.println(line + " ERROR: " + ex.getMessage());
System.err.println(line + " ERROR: " + ex.getMessage());
}
}
else {
recordErrors.println(line + " ERROR: Invalid record length.");
System.err.println(line + " ERROR: Invalid record length.");
}
}
}
}
}
catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException. Please ensure the directory is configured properly.");
}
return stockQueue;
}
However, the error file is always blank.
I've tried calling the .flush() and .close() methods. System.err is outputting so I know the code is being run. I've tried instantiating the PrintStream outside of the try-with-resources, no change.
I've tried calling the method at earlier points in the code (i.e. right after instantiation of the printStream, and in the if{} block) and it does output to the error file. It's only within the catch{} and else{} blocks (where I actually need it to work) that it refuses to print anything. I've also tried storing the error data and using a loop after the blocks to print the data and it still won't work. See code block:
public static LinkedQueue<Stock> getStockData(LinkedQueue<Stock> stockQueue, String startPath) throws Exception {
File dir = new File(getValidDirectory(startPath));
LinkedQueue errors = new LinkedQueue();
try (PrintStream recordErrors = new PrintStream(new File("EODdataERRORS.txt"))) {
for (File name : dir.listFiles()) {
if (name.isDirectory()) {
getStockData(stockQueue, name.getPath());
}
else if (name.canRead()) {
Scanner readFile = new Scanner(name);
readFile.nextLine();
while (readFile.hasNext()) {
String line = readFile.nextLine();
String[] lineArray = line.split(",+");
if (lineArray.length == 8) {
try {
Stock stock = new Stock(name.getName().replaceAll("_+(.*)", ""));
stock.fromRecord(lineArray);
stockQueue.enqueue(stock);
}
catch (Exception ex) {
errors.enqueue(line + " ERROR: " + ex.getMessage());
System.err.println(line + " ERROR: " + ex.getMessage());
}
}
else {
errors.enqueue(line + " ERROR: Invalid record length.");
System.err.println(line + " ERROR: Invalid record length.");
}
}
}
}
while (!errors.isEmpty()) {
recordErrors.println(errors.dequeue());
}
}
catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException. Please ensure the directory is configured properly.");
}
return stockQueue;
}
Edit
Code has been edited to show instantiation of the PrintStream only once. The error persists. I am sorry there is no Repex, I cannot recreate this error except for in this specific case.
I have solved the issue. I'm not really sure what the issue was, but it appears to have something to do with the PrintStream being instantiated in a method other than the main{} method. This would also explain why I was unable to recreate this error, try as I might.
As such, I've solved it by simply storing the errors in a list and printing them in the main{} method.
public static void getStockData(LinkedQueue<Stock> stockQueue, LinkedQueue<String> errorQueue, String startPath) {
File dir = new File(getValidDirectory(startPath));
try {
for (File name : dir.listFiles()) {
if (name.isDirectory()) {
getStockData(stockQueue, errorQueue, name.getPath());
}
else if (name.canRead()) {
Scanner readFile = new Scanner(name);
readFile.nextLine();
while (readFile.hasNext()) {
String line = readFile.nextLine();
String[] lineArray = line.split(",+");
if (lineArray.length == 8) {
try {
Stock stock = new Stock(name.getName().replaceAll("_+(.*)", ""));
stock.fromRecord(lineArray);
stockQueue.enqueue(stock);
}
catch (Exception ex) {
errorQueue.enqueue(line + "; ERROR: " + ex.getMessage());
System.err.println(line + "; ERROR: " + ex.getMessage());
}
}
else {
errorQueue.enqueue(line + "; ERROR: Invalid record length.");
System.err.println(line + "; ERROR: Invalid record length.");
}
}
}
}
}
catch (FileNotFoundException ex) {
System.err.println("FileNotFoundException. Please ensure the directory is configured properly.");
}
}
This has the downside of taking up more memory, but I see no other way to get this to work the way I want it to. Thanks for the help!

File.createTempFile in Java getting Incompatible type error

Till now my code works fine where I am creating file in temporary directory and processing it.
But now I am trying to provide specific directory where I actually want to create xml file. So in method createTmpXmlFile
private static Path createTmpXmlFile(final String prefix) {
try {
log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
I changed from
return Files.createTempFile(prefix, XML_SUFFIX);
to
return File.createTempFile(prefix, XML_SUFFIX, "/tmp/in");
and I get following error:
java: incompatible types: java.lang.String cannot be converted to java.io.File.
If I change the logic here then its affecting other method that are calling createTmpXmlFile method.
I really don't understand how to resolve this issue. Below is my code:
#Slf4j
public class InputCS implements Runnable {
public static final String XML_SUFFIX = ".xml";
#Value("${gleifdataimporter.file.dir}")
private String gleifZipFile;
private void processleifZipFile() {
final AtomicBoolean isInsideLeiRecord = new AtomicBoolean();
isInsideLeiRecord.set(false);
final StringBuilder currentLeiRecordXml = new StringBuilder();
try (FileSystem zipFs = FileSystems.newFileSystem(jobRunner.getInputZipPath(), null)) {
Path tmpXMLPath = xmlFileFromLeiZipFile(zipFs);
try (Stream<String> lines = Files.lines(tmpXMLPath)) {
AtomicInteger processedLinesCounter = new AtomicInteger();
AtomicInteger currentLineNumber = new AtomicInteger();
lines.sequential().forEach(handleLineAndIncrementLineNumber(isInsideLeiRecord, currentLeiRecordXml, processedLinesCounter, currentLineNumber));
log.info("{} lines of XML file inside LEIF input ZIP file {} processed.", processedLinesCounter.get(), jobRunner.getInputZipPath());
}catch (IOException e) {
throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
} finally {
Files.delete(tmpXMLPath);
}
} catch (IOException e) {
throw new IllegalStateException("Problem reading input file at " + jobRunner.getInputZipPath() + ".", e);
}
}
private Path xmlFileFromLeiZipFile(FileSystem zipFs) { //extracts the xml file from zip file
log.info("Input file {} exists: {}", jobRunner.getInputZipPath(), Files.exists(jobRunner.getInputZipPath()));
Path tmpXmlPath = createTmpXmlFile("leif__" + System.currentTimeMillis());
for (Path rootDir : zipFs.getRootDirectories()) {
try (Stream<Path> files = treeAt(rootDir)) {
log.info("Trying to extract LEIF XML file from ZIP file into {}.", tmpXmlPath);
final Path xmlFileInsideZip = files
.filter(isNotADir())
.filter(Files::isRegularFile)
.findFirst()
.orElseThrow(() -> new IllegalStateException("No file found in LEI ZIP file."));
log.info("Path to LEIF XML file inside ZIP file: {}.", xmlFileInsideZip);
return copyReplacing(xmlFileInsideZip, tmpXmlPath);
}
}
throw new IllegalStateException("No file found in LEI ZIP file " + jobRunner.getInputZipPath() + ".");
}
private static Path createTmpXmlFile(final String prefix) {
try {
log.info("Creating temporary file {}{}", prefix, XML_SUFFIX);
return Files.createTempFile(Paths.get(gleifZipFile), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
#NotNull
private static Path copyReplacing(Path from, Path to) {
requireNonNull(from, "Trying to copy from a path, which is null to path " + to + "."); //trying to copy file where no xml file exist in root directory
requireNonNull(to, "Trying to copy from path " + from + " to a path, which is null.");
try {
return Files.copy(from, to, REPLACE_EXISTING);
} catch (IOException e) {
throw new IllegalStateException("Cannot copy from " + from + " to " + to + ". ", e);
}
}
}
As suggested by Slaw, use Files#createTempFile(Path,String,String,FileAttribute...) to specify the directory to create temp file.
Use Paths#get(String,String...) for java 7 or 8, or Path#of(String,String...) for java 11 or later to convert String to Path. Further reading: Paths.get vs Path.of
private static Path createTmpXmlFile(final String prefix) {
try {
// Java 11 or later
// return Files.createTempFile(Path.of("/tmp/in"), prefix, XML_SUFFIX);
// Java 8
return Files.createTempFile(Paths.get("/tmp/in"), prefix, XML_SUFFIX);
} catch (IOException e) {
throw new IllegalStateException("Could not create tmp file at " + prefix + XML_SUFFIX + ". ", e);
}
}
File.createTempFile is expecting a File object as third parameter. Just wrap your "/tmp/in" into a File
=> return File.createTempFile(prefix, XML_SUFFIX, new File("/tmp/in")); and you should be good to go.
so you can do:
File.createTempFile("prefix", "suffix", new File("/tmp/in"));
Or using NIO (recommended)
Files.createTempFile(Paths.get("/tmp/in"), "prefix", "suffix");

Get FileStore object for any given path

Edit: I recognize that FileSystem.getDefault() will give me what I was looking for in my original question statement. I am attempting to use FileSystem.getFileSystem(URI) to get the FileSystem for any given path.
I am attempting to develop some code that will give me a java.nio.file.FileSystem object for a given path.
Here is some grossly simplified example code to give a better idea of what is being attempted:
public FileSystem getCwdFilesystem()
{
URI cwdUri = null;
String delimiter = "";
try
{
_cwd = System.getProperty("user.dir");
cwdUri = new URI("file", delimiter + _cwd, null);
}
catch (URISyntaxException ue)
{
System.out.println("URI Creation failure on URI: " + _cwd);
ue.printStackTrace();
System.exit(1);
}
System.out.println("Filestore data for CWD: " + cwdUri.toString());
return (FileSystems.getFileSystem(cwdUri));
}
Upon execution, an exception is throw on the last line of code:
Filestore data for CWD: file:/Users/redacted/Documents/Java%20Projects/ExampleCode
Exception in thread "main" java.lang.IllegalArgumentException: Path component should be '/'
at sun.nio.fs.UnixFileSystemProvider.checkUri(UnixFileSystemProvider.java:77)
at sun.nio.fs.UnixFileSystemProvider.getFileSystem(UnixFileSystemProvider.java:92)
at java.nio.file.FileSystems.getFileSystem(FileSystems.java:217)
at examplecode.FilesystemCapacity.getCwdFilesystem(FilesystemCapacity.java:54)
at examplecode.FilesystemCapacity.main(FilesystemCapacity.java:33)
Java Result: 1
When I make a small update to the delimiter variable:
String delimiter = "/";
I get a different error message thrown from the same place:
Filestore data for CWD: file://Users/redacted/Documents/Java%20Projects/ExampleCode
Exception in thread "main" java.lang.IllegalArgumentException: Authority component present
at sun.nio.fs.UnixFileSystemProvider.checkUri(UnixFileSystemProvider.java:73)
at sun.nio.fs.UnixFileSystemProvider.getFileSystem(UnixFileSystemProvider.java:92)
at java.nio.file.FileSystems.getFileSystem(FileSystems.java:217)
at examplecode.FilesystemCapacity.getCwdFilesystem(FilesystemCapacity.java:54)
at examplecode.FilesystemCapacity.main(FilesystemCapacity.java:33)
Java Result: 1
Adding additional "/" characters to the delimiter simply gets me the first error message again.
What am I doing wrong?
I found a reference I had previously missed on the last page of the NIO.2 document trail.
I wrote up some test code that gave me exactly what I needed:
public void getPathFilesystem(String path)
{
try
{
URI rootURI = new URI("file:///");
Path rootPath = Paths.get(rootURI);
Path dirPath = rootPath.resolve(path);
FileStore dirFileStore = Files.getFileStore(dirPath);
printFileStore(dirFileStore, path);
}
catch (IOException | URISyntaxException e)
{
e.printStackTrace();
}
}
public void printFileStore(FileStore filestore, String path)
{
try
{
System.out.println("Name: " + filestore.name());
System.out.println("\tPath: " + path);
System.out.println("\tSize: " + filestore.getTotalSpace());
System.out.println("\tUnallocated: " + filestore.getUnallocatedSpace());
System.out.println("\tUsable: " + filestore.getUsableSpace());
System.out.println("\tType: " + filestore.type());
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}

loading class at runtime in java ClassNotFoundException

I am having problems calling classes at run time in java
Im basically making a plugin framework
it starts off by opening plugin/Plugins.cfg and parses the test into a map..
EX text in cfg file
1 = myplugin
2 = plugin2
(each plugins main class is: plugin.(plugin name).main.class)
as you can see it loads each value from the map and trys to run its main class
public static void loadPlugins()
{
int x = hackers.core.startup.InitializeGame.map.size();
for (int i = 1; i<=x;i++)
{
String className = hackers.core.startup.InitializeGame.map.get(i + "");
File file = new File(System.getProperty("user.dir") + File.separator + "plugins" + File.separator + className);
URL url = null;
try {
url = file.toURI().toURL();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
try {
Class cls = cl.loadClass("plugin." + className + ".main");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(className);
}
}
Class cls = cl.loadClass("plugin." + className + ".main");
^line gives me the error: java.lang.ClassNotFoundException: plugin.myplugin.main
anyone know whats wrong here?, or any suggestions, I have looked at an API for it but it was confusing to me and lacks documentation.
Your file doesn't point to a valid class or jar file.
Debug the following line; you will notice it's path isn't an existing path in your file system.
File file = new File(System.getProperty("user.dir") + File.separator + "plugins" + File.separator + className);
I would assume that you've forgotten to include .class in the className.

InputStream is null

In a program I'm working on I have
String cwd;
String file_separator;
public ConfigLoader()
{
cwd = get_cwd();
file_separator = get_file_separator();
try
{
Properties c = new Properties();
InputStream in = this.getClass().getClassLoader().getResourceAsStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");
c.load(in);
}
except (Exception e) { e.printStackTrace(); }
}
public String get_file_separator()
{
File f = new File("");
return f.separator;
}
public String get_cwd()
{
File cwd = new File("");
return cwd.getAbsolutePath();
}
For some reason, though, c.load(in); causes a NullPointerException. The exception comes from in == NULL being true. I can't figure out why because
System.out.println(cwd + file_separator + "data" + file_separator +
"configuration.properties");
prints
/users/labnet/st10/jjb127/workspace/Brewer-Client/data/configuration.properties
which is the location of the file I'm wanting to use.
Thoughts?
getResourceAsStream is meant to search for files on the classpath and not for accessing the local file system. You will have to use FileInputStream for this case.
InputStream in = new FileInputStream(cwd +
file_separator + "data" + file_separator + "configuration.properties");

Categories

Resources