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)
Related
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);
}
}
All.. task - Open file but don't write anything. When data comes from a thread and request to log it, write it to the file. When request to stop logging, close the file. File should be initially opened in append mode. I have written such code in many languages but not in Java. Everything I come across talks about a single method to open, write(s) and close. What I need is to open a the file and return a pointer to the file (FileWriter). Use that file pointer later to both write to and eventually close the file. My code is below:
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class LogIt
{
public static FileWriter outLog = null;
public static void main(String[] args) throws IOException
{
Logging lFile = new Logging() ;
Logging.OpenLogFile(primeClass.theLogFile);
Logging.CloseLogFile() ;
}
// end main
public static void OpenLogFile(String filename) throws IOException
{
// open output file
try
{
// if file doesn't exists, then create it
File file =new File(filename);
if (!file.exists())
{
file.createNewFile();
System.out.println("Logfile " + filename + " did not exist!");
}
FileWriter outLog = new FileWriter(filename, true);
System.out.println("logFile " + filename + " has been opened for append mode");
}
catch (IOException e)
{
System.out.println("Unable to Open log file " + filename);
System.err.println("Error: " + e.getMessage());
}
}
// End of OpenLogFile
public static void WriteLogFile(String line2Write) throws IOException
{
// write output to opened file
try
{
outLog = new FileWriter(line2Write);
outLog.write(line2Write);
}
catch (IOException e)
{
System.out.println("Unable to write to " + PrimeClass.theLogFile);
System.out.println("Error: " + e.getMessage());
}
} // end OpenLogFile
public static void CloseLogFile() throws IOException
{
try
{
outLog.close();
System.out.println("file closed");
}
catch (IOException e)
{
System.out.println("Unable to close logfile " + PrimeClass.theLogFile);
System.out.println("Error: " + e.getMessage());
}
}
// end CloseLogFile
}
// end LogIt class
The class compiles and if the file doesn't exist its created. However, without writing to the file, an attempt to close the file results in a null pointer exception. I was thinking of building 2 methods to set and get the "outLog" value. Also, it appears that when the write occurred it actually started using the output to generate files on the directory and not written to the actual file.
Suggestions?
You're declaring a local FileWriter instead of assigning to the member variable.
NB You don't need to create the file if it doesn't exist. `new FileWriter()' already does that.
I'm trying to create a program that will read in an XML-based file and that will basically rewrite it in a more human friendly way, but I keep running into XMLStreamExceptions.
Here is what I have now
`import java.io.File;
/* main purpose of this class is to read and write an XML document
using tenants of STaX parsing. Eventually this should turn into a
class that will trim all but the outer 20% of the page
*/
public class XMLReader {
public static void main(String args[]) {
XMLInputFactory factory = XMLInputFactory.newInstance();
System.out.println("FACTORY:" + factory);
/*
//TODO: make input and output file take args from command line
using the programs mike sent as a reference.
File file =null;
if(args.length > 0) {
file = new File(args[0]);
}
*/
InputStream in = null; //initializing the file we will read
XMLEventReader reader = null; //intializing the eventreader
try {
in = new FileInputStream("/home/bzifkin/Proteus2/homer/src/main/java/ciir/proteus/parse/1105979_djvu.xml");
} catch (FileNotFoundException e) {
System.out.println("Could not find the file. Try again.");
}
try {
reader = factory.createXMLEventReader(in);
}
catch (XMLStreamException e) {
System.out.println("There was an XML Stream Exception, whatever that means");
}
}
}
This is the stack trace I get on the XMLStreamException
Message: expected start or end tag at com.sun.xml.internal.stream.XMLEventReaderImpl.nextTag(XMLEventReaderImpl.java:235)
at ciir.proteus.parse.XMLReader.main(XMLReader.java:61)
If I understand the comments right, you get a FileNotFoundException first, then XMLStreamException.
That sounds reasonable, because if opening the file fails, your code is printing an error message, but continues to process the undefined (null) InputStream "in".
Do something like this instead:
try {
in = new FileInputStream("/home/bzifkin/Proteus2/homer/src/main/java/ciir/proteus/parse/1105979_djvu.xml");
try {
reader = factory.createXMLEventReader(in);
}
catch (XMLStreamException e) {
System.out.println("There was an XML Stream Exception, whatever that means");
}
} catch (FileNotFoundException e) {
System.out.println("Could not find the file. Try again.");
}
I'm trying to open a pdf located in a ressource folder with my application.
It does work on the emulator but nothing happens when I try on the exported application.
I'm guessing I'm not using the rigth path but do not see where I'm wrong. The getRessource method works very well with my images.
Here is a code snippet :
public void openPdf(String pdf){
if (Desktop.isDesktopSupported()) {
try {
URL monUrl = this.getClass().getResource(pdf);
File myFile = new File(monUrl.toURI());
Desktop.getDesktop().open(myFile);
} catch (IOException ex) {
// no application registered for PDFs
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
I'm referring to the pdf variable this way : "name_of_the_file.pdf"
Edit: I've pasted the whole method
Ok, solved it. The file being located in a Jar, the only way to get it was through a inputsteam/outstream and creating a temp file.
Here is my final code, which works great :
public void openPdf(String pdf){
if (Desktop.isDesktopSupported())
{
InputStream jarPdf = getClass().getClassLoader().getResourceAsStream(pdf);
try {
File pdfTemp = new File("52502HPA3_ELECTRA_PLUS_Fra.pdf");
// Extraction du PDF qui se situe dans l'archive
FileOutputStream fos = new FileOutputStream(pdfTemp);
while (jarPdf.available() > 0) {
fos.write(jarPdf.read());
} // while (pdfInJar.available() > 0)
fos.close();
// Ouverture du PDF
Desktop.getDesktop().open(pdfTemp);
} // try
catch (IOException e) {
System.out.println("erreur : " + e);
} // catch (IOException e)
}
}
You mentioned that it is running on Emulator but not on the application. There is high probability that the platform on which the application is running does not support Desktop.
Desktop.isDesktopSupported()
might be returning false. Hence no stack trace or anything.
On Mac, you can do:
Runtime runtime = Runtime.getRuntime();
try {
String[] args = {"open", "/path/to/pdfFile"};
Process process = runtime.exec(args);
} catch (Exception e) {
Logger.getLogger(NoJavaController.class.getName()).log(Level.SEVERE, "", e);
}
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;