getResourceAsStream() works on Windows but not on Linux - java

I have a following class in my project:
package com.test.schedule.payloads;
import com.google.common.base.Charsets;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import java.io.IOException;
import java.io.InputStreamReader;
/**
* Loads payload from file
*/
public class FilePayload{
private static final Logger LOGGER = Logger.getLogger(FilePayload.class);
private final String filename;
public FilePayload(String filename) {
this.filename = filename;
}
public String getAsString() {
try {
return IOUtils.toString(new InputStreamReader(FilePayload.class.getResourceAsStream(filename), Charsets.UTF_8));
} catch (IOException e) {
LOGGER.error("Error while loading file: '" + filename +'\'', e);
return "";
}
}
}
In resources directory of my project (maven one) I have file in following path:
com/test/schedule/payloads/schedule-payload.xml
When I execute getAsString() with filename equal to "schedule-payload.xml" on Windows everything works fine. But when the same code is executed on Linux server it returns null on getResourceAsStream(). I have no idea how to fix it so code works both on Windows and Linux. Any help would be very appreciated.

Check, that everything on your path to this file "com/test/schedule/payloads/schedule-payload.xml" is lowercase, as linux paths are case sensitive and windows paths are not case sensitive.

Related

Copying file using Apache Commons FileUtils

On the first run, I want to copy the given File to a new location with a new file name.
Every subsequent run should overwrite the same destination file created during first run.
During first run, the destination file does not exist. Only the directory exists.
I wrote the following program:
package myTest;
import java.io.File;
import java.io.IOException;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String[] args) {
TestFileCopy fileCopy = new TestFileCopy();
File sourceFile = new File("myFile.txt");
fileCopy.saveFile(sourceFile);
File newSourceFile = new File("myFile_Another.txt");
fileCopy.saveFile(newSourceFile);
}
}
class TestFileCopy {
private static final String DEST_FILE_PATH = "someDir/";
private static final String DEST_FILE_NAME = "myFileCopied.txt";
public void saveFile(File sourceFile) {
URL destFileUrl = getClass().getClassLoader().getResource(DEST_FILE_PATH
+ DEST_FILE_NAME);
try {
File destFile = Paths.get(destFileUrl.toURI()).toFile();
FileUtils.copyFile(sourceFile, destFile);
} catch (IOException | URISyntaxException e) {
e.printStackTrace();
}
}
}
However, this throws null pointer exception on the following line:
File destFile = Paths.get(destFileUrl.toURI()).toFile();
What am I missing?
Directory someDir is directly under my project's root directory in eclipse.
Both source files myFile.txt and myFile_Another.txt exists directly under my project's root directory in eclipse.
I used this and it works as I am expecting:
public void saveFile1(File sourceFile) throws IOException {
Path from = sourceFile.toPath();
Path to = Paths.get(DEST_FILE_PATH + DEST_FILE_NAME);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);
}
Using Java nio.

tilde (~) in java File path

Any idea why this works fine even on a Windows environment ?
Can you point me to some docs which explains why this works ?
I tried to look for it with no results.
package com.my.example;
import org.junit.Test;
import java.io.File;
public class TestPathCreation
{
#Test
public void testPathCreation() throws Exception {
final String path = "~/.my/dir";
System.out.println(path);
File f = new File(path);
System.out.println(f.mkdirs()); // true
}
}

getClassLoader().getResourceAsStream method returns null for a file with ".LIB" extension

I'm trying to load a file from resources/ path using
getClassLoader().getResourceAsStream("file.LIB")
but the method always returns null, unless I rename the file into another extension, say ".dll".
I've looked into the official Java documentation, but to no avail.
Why does the method acts strange on that file type?
Note: I'm using JDK 1.8.0_111 x86 (due to constraints on that lib file, which only works well with a 32-bit JVM)
It does works for me, you need to be sure what exactly you are doing with lib file.
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class FileHelper {
public String getFilePathToSave() {
Properties prop = new Properties();
String filePath = "";
try {
InputStream inputStream =
getClass().getClassLoader().getResourceAsStream("abc.lib");
prop.load(inputStream);
filePath = prop.getProperty("json.filepath");
} catch (IOException e) {
e.printStackTrace();
}
return filePath;
}
public static void main(String args[]) {
FileHelper fh = new FileHelper();
System.out.println(fh.getFilePathToSave());
}
}

While creating this java program in oracle db. Im facing some errors. CAn anyone tell me the way to compile it. the code is as follows

Below code is working properly in eclipse. But I,m trying to create this source in oracle 11g Db. While creating it throws some warnings.
create or replace
and compile java source named "Noitime"
as
package com;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.FileTime;
public class Noitime {
public String attr(String filepath,String filename)
{
long time = System.currentTimeMillis();
FileTime fileTime = FileTime.fromMillis(time);
Path path = Paths.get(filepath,filename);
try {
Files.setLastModifiedTime(path, fileTime);
return "Success";
} catch (IOException e) {
System.err.println(e);
return "Fail";
}
}
}
You appear to have garbled the error/warning message, but I think that it is telling you that you should be using the pathname "com/Noitime.java" when compiling. The pathname you use should correspond to the full class name, and the full class name is "com.Noitime".

How can I load a file relative to a class's package?

I have the file allDepartments.json in a subdirectory called fixtures, to which I want to access from the Fixture.java class.
This is my Fixture.java code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public final class Fixture {
private static final String FIXTURES_PATH = "";
private final String fixture;
public Fixture(String fixtureName) throws IOException {
fixture = new String(Files.readAllBytes(Paths.get(FIXTURES_PATH + fixtureName)));
}
public final String getFixture() {
return fixture;
}
}
However every time he tries to access the file I get a java.nio.file.NoSuchFileException: allDepartments.json...
I have heard of the getResource() method and tried every combination possible of it, without success.
I need this to store multi-line strings for my JUnit tests.
What can I do?
The NIO.2 API can't be used to read files that are effectively project resources, i.e. files present on the classpath.
In your situation, you have a Maven project and a resource that you want to read during the unit test of the application. First, this implies that this resources should be placed under src/test/resources so that Maven adds it automatically to the classpath during the tests. Second, this implies that you can't use the Files utility to read it.
You will need to resort to using a traditional BufferedReader:
public Fixture(String fixtureName) throws IOException {
try (BufferedReader br = new BufferedReader(new InputStreamReader(Fixture.class.getResourceAsStream(FIXTURES_PATH + fixtureName)))) {
// do your thing with br.readLine();
}
}
Note the path given to getResourceAsStream is either relative to the current class or absolute. If the resources is located in src/test/resources/folder/allDepartments.json then a valid path would be /folder/allDepartments.json.
Add allDepartments.json to the.classpath file of the project and java should be able to pick it up.
Refer this topic if you want to know how to add a file to class path from eclipse
when you run Fixtures.java the relative path would be
../fixtures/allDepartments.json
try using this path.
Thank you all for helping and suggestions.
Thanks to you I was able to put things working, so here is the trick (which I guess only works for Maven projects):
I moved the allDepartments.json file to the default src/test/resources folder as suggested by you guys. I didn't even had to modify the pom.xml. And now everything works!
So this is my project structure now:
And the final Fixture.java code is:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.stream.Collectors;
public final class Fixture {
private final String fixture;
public Fixture(String fixtureName) throws IOException {
fixture = this.readFile(fixtureName);
}
private String readFile(String fileName) throws IOException {
final InputStream in = this.getClass().getClassLoader().getResource("fixtures/" + fileName).openStream();
final BufferedReader buffer = new BufferedReader(new InputStreamReader(in));
try {
return buffer.lines().collect(Collectors.joining("\n"));
} finally {
buffer.close();
}
}
public final String getFixture() {
return fixture;
}
}

Categories

Resources