Locally, everything works well for me.
When I build a project and run it on the server it will not load images.
How do I change it to load as getInputStream, or some other way to work in a .jar file?
I use this code:
private final Path root = Paths.get("images");
#Override
public Resource load(String filename){
try{
Path file = root.resolve(filename);
Resource resource = new UrlResource(file.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new RuntimeException("Could not read the file!");
}
} catch (MalformedURLException e) {
throw new RuntimeException("Error: " + e.getMessage());
}
}
I tried to use from this link, but it won't show me the image after BufferedReader:
https://www.baeldung.com/java-classpath-resource-cannot-be-opened
Related
For some reason i have to place my *.properties files outside of java app. When the file km.properties resides in java/src/resources/km.properties the code reads the file but when i place the same file in C:\Users\abc\Desktop\km.properties
it throws
Exception: java.io.FileNotFoundException: property file 'C:\Users\abc\Desktop\km.properties' not found in the classpath
Exception in thread "main" java.lang.NullPointerException
at com.ir.Constants.<init>(Constants.java:44)
at com.Constants.main(Constants.java:64)
here is my code
public class Constants {
public Constants(){
System.out.println(System.getenv("km_config"));
try {
Properties prop = new Properties();
String propFileName = System.getenv("km_config");
inputStream = getClass().getClassLoader().getResourceAsStream(propFileName);
if (inputStream != null) {
prop.load(inputStream);
} else {
throw new FileNotFoundException("property file '" + propFileName + "' not found in the classpath");
}
}
catch (IOException e) {
System.out.println("Exception: " + e);
}
catch (Exception e) {
System.out.println("Exception: " + e);
} finally {
try {
inputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public static void main(String[] args) throws Exception {
Constants c = new Constants();
System.out.println(Constants.DB_PATH1);
System.out.println(Constants.GIT_REPO_PATH);
System.out.println(Constants.GIT_MAIN_BRANCH_NAME);
System.out.println(Constants.TAGGER_PATH);
}
Constants.java:44 is
inputStream.close();
Constants.java:64 is
Constants c = new Constants();
please help me i need to place km.properies file any where outside of the java app
command results in
echo %km_config%
C:\Users\abc\Desktop\km.properties
The API ClassLoader::getResourceAsStream(String) has a search path which is the classpath. Actually you are right that the configuration file should not be bundled with your .class files and read from the filesystem of the target machine instead.
Thus your API call becomes:
Properties conf = new Properties();
conf.load(new InputStreamReader(new FileInputStream(new File(file)));
Note: I did not specify a charset for converting the stream of bytes to a stream of character because I want the JVM to pick whatever character is the default for the system.
For testing I suggest you:
put the configuration file in a known location out of the sources (the Desktop) or anyway ignored by the version control system
pass the value as a system property (like -Dfile=C:\Users\me\Desktop\km.properties)
I am trying write to a csv file. After the execution of the code bellow the csv file is still empty.
File is in folder .../webapp/resources/.
This is my dao class:
public class UserDaoImpl implements UserDao {
private Resource cvsFile;
public void setCvsFile(Resource cvsFile) {
this.cvsFile = cvsFile;
}
#Override
public void createUser(User user) {
String userPropertiesAsString = user.getId() + "," + user.getName()
+ "," + user.getSurname() +"\n";;
System.out.println(cvsFile.getFilename());
FileWriter outputStream = null;
try {
outputStream = new FileWriter(cvsFile.getFile());
outputStream.append(userPropertiesAsString);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
#Override
public List<User> getAll() {
return null;
}
}
This is a part of beans.xml.
<bean id="userDao" class="pl.project.dao.UserDaoImpl"
p:cvsFile="/resources/users.cvs"/>
Program compiles and doesn't throw any exceptions but CSV file is empty.
If you're running your app in IDE, the /webapp/resources used for running app will differ from the /webapp/resources in your IDE. Try to log full path to file and check there.
try using outputStream.flush() as the final statement in the first of the try block.
I think you're looking at the wrong file. If you specify an absolute path /resources/users.cvs, then it probably won't be written into the a folder relative to the webapp. Instead, it will be written to /resources/users.cvs
So the first step is to always log an absolute path to make sure the file is where you expect it.
Try with this code, it will at least tell you where the problem lies (Java 7+):
// Why doesn't this method throw an IOException?
#Override
public void createUser(final User user)
{
final String s = String.format("%s,%s,%s",
Objects.requireNonNull(user).getId(),
user.getName(), user.getSurname()
);
// Note: supposes that .getFile() returns a File object
final Path path = csvFile.getFile().toPath().toAbsolutePath();
final Path csv;
// Note: this supposes that the CSV is supposed to exist!
try {
csv = path.toRealPath();
} catch (IOException e) {
throw new RuntimeException("cannot locate CSV " + path, e);
}
try (
// Note: default is to TRUNCATE the destination.
// If you want to append, add StandardOpenOption.APPEND.
// See javadoc for more details.
final BufferedWriter writer = Files.newBufferedWriter(csv,
StandardCharsets.UTF_8);
) {
writer.write(s);
writer.newLine();
writer.flush();
} catch (IOException e) {
throw new RuntimeException("write failure", e);
}
}
File oldfile = new File("C:\\NewText Document.txt");
File newfile = new File("C:\\Hello Buddy.txt");
if (oldfile.renameTo(newfile))
{
System.out.println("Rename succesful");
}
else
{
System.out.println("Rename failed");
}
I'm planning on developing it into a file normalizer, but I just want to get this done first.
I've tried using the absolute path, makes no difference. Constantly returning "Rename Failed".
Use move method of Files class. Worked for me ;)
Java doc
If you are using Java 7 then try this:
final File oldfile = new File("C:\\NewText Document.txt");
final File newfile = new File("C:\\Hello Buddy.txt");
final Path source = oldfile.toPath();
final Path dest=newfile.toPath();
try {
Files.move(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
FileChooser();
File oldfile = new File(fileName);
File newfile = new File(fileName.substring(0, 21) + "hello world.txt");
if (!oldfile.exists())
{
try
{
oldfile.createNewFile();
}
catch (IOException ex)
{
System.out.println(ex);
}
}
else
{
if (oldfile.renameTo(newfile))
{
System.out.println("Rename succesful");
}
else
{
System.out.println("Rename failed");
}
}
This is my new code, it works using a file chooser,but currently it only works if i choose the file from my desktop, hence the hardcoded substring.
I am trying to create a directory to store my application's files in the BlackBerry's internal memory. Here's the code:
String uri = "file:///store/testapp/";
FileConnection dir;
try {
dir = (FileConnection)Connector.open(uri, Connector.READ_WRITE);
if (!dir.exists()){
dir.mkdir();
}
dir.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
When I run the above I get an IOException with the message "File System Error (12)". Looking this up in the list of BlackBerry constant values this corresponds to "The operation requested is invalid.". Why can't I create the testapp directory?
You can create your own directories only in: "file:///store/home/user/"
You should only create directories in "file:///store/home/user/" or "file:///store/home/samples/" only;
For creating a directory:
public void createDirectory()
{
FileConnection file=null;
try
{
String Path="file:///store/home/user/Abc/"; // or path="file:///store/home/samples/Abc/"
file = (FileConnection)Connector.open(Path);
if(!file.exists())
file.mkdir();
file.close();
}
catch (IOException e)
{
try
{
if(file!=null)
{
file.close();
}
System.out.println("==============Exception: "+e.getMessage());
}
catch (IOException e1)
{
}
}
}
There is different in "file:///store/home/user/Abc/" and "file:///store/home/user/Abc"
If you put like "file:///store/home/user/Abc" then it take the "Abc" as file;
If you put like "file:///store/home/user/Abc/" then it take the "Abc" as directory;
I'm trying to package up resources into a jar, but I'm having trouble getting Flying Saucer to find the css on the classpath - I can't construct a URL easily to be able to resolve this seamlessly.
Does Flying saucer have a way of specifying resource packages on the classpath to resolve items and images?
Note: I'm running this in a webstart application that does not have file system writing permissions, so jar expansion is not really an option.
You should implement a UserAgentCallback that you feed to the XHTMLPanel, something like this:
private static class UAC extends NaiveUserAgent {
#Override
public String resolveURI(String uri) {
return uri;
}
#Override
protected InputStream resolveAndOpenStream(String uri) {
java.io.InputStream is = null;
URL url = UAC.class.getResource(uri);
if (url == null) {
XRLog.load("Didn't find resource [" + uri + "].");
return null;
}
try {
is = url.openStream();
}
catch (java.net.MalformedURLException e) {
XRLog.exception("bad URL given: " + uri, e);
}
catch (java.io.FileNotFoundException e) {
XRLog.exception("item at URI " + uri + " not found");
}
catch (java.io.IOException e) {
XRLog.exception("IO problem for " + uri, e);
}
return is;
}
}
XHTMLPanel panel = new XHTMLPanel(new UAC());
My solution is
private static class UserAgentCallback extends ITextUserAgent {
public UserAgentCallback(ITextOutputDevice outputDevice, SharedContext sharedContext) {
super(outputDevice);
setSharedContext(sharedContext);
}
#Override
public String resolveURI(String uri) {
return uri;
}
#Override
protected InputStream resolveAndOpenStream(String uri) {
java.io.InputStream is = null;
URL url = null;
try {
url = new ClassPathResource("/META-INF/pdfTemplates/" + uri).getURL();
} catch (IOException e) {
XRLog.exception("bad URL given: " + uri, e);
}
if (url == null) {
XRLog.load("Didn't find resource [" + uri + "].");
return null;
}
try {
is = url.openStream();
} catch (java.net.MalformedURLException e) {
XRLog.exception("bad URL given: " + uri, e);
} catch (java.io.FileNotFoundException e) {
XRLog.exception("item at URI " + uri + " not found");
} catch (java.io.IOException e) {
XRLog.exception("IO problem for " + uri, e);
}
return is;
}
}
and invocation:
renderer.getSharedContext()
.setUserAgentCallback(new UserAgentCallback(renderer.getOutputDevice(), renderer.getSharedContext()));
It would seem that flying saucer does not have a way of specifying resources on the classpath, so I work around by making a classpath: protocol url handler at the linked question
Post Implementation Findings
It would seem that the some of the premises of this question are invalid. After writing my own classpath URL loader, I found that you need to request <all-permissions/> in the jnlp to be able to use URL.setURLStreamHandlerFactory(). In fact, you need to request all permissions to do just about anything fancy (even though you're only modifying your own sand-box). See the full list here.
In short, this means that I am able to extract files to the operating system. But it's nice having a classpath loader now...