This question already has answers here:
What is the proper way to store app's conf data in Java?
(6 answers)
Closed 9 years ago.
I'm making an application using databases in Java (compiled as JAR). In order to connect to the database, the user must enter the database's address. It would be a pain to remember/type the address every time you want to use the program.
Thus, I want to save the address to a text file somewhere...but where? I want this application to be accessible to anyone on any operating system, and I'd prefer not to have my JAR in a folder.
Is it possible, maybe, to write/read from a text file located within the JAR itself?
Like Sotirios Delimanolis said you can create and save a properties file.
It is very simple to do it please have a look at the example below (see the original the post)
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class WritePropertiesFile {
public static void main(String[] args) {
try {
Properties properties = new Properties();
properties.setProperty("favoriteAnimal", "marmot");
properties.setProperty("favoriteContinent", "Antarctica");
properties.setProperty("favoritePerson", "Nicole");
File file = new File("test2.properties");
FileOutputStream fileOut = new FileOutputStream(file);
properties.store(fileOut, "Favorite Things");
fileOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I would not suggest you save the properties file into the jar file however it is possible to do so.
Please follow the stackoverflow answer at: how to write into a text file in Java
You can open a file anywhere in your jar using e.g. ClassLoader.getResourceAsStream()
Here's what worked for me. I simply used the path System.getProperty("user.home") as my file's location. This is operating system neutral.
Try the Java Preferences API to store user data like this.
Storing data in the application folder will be problematic (e.g., user might not have permission, application might be signed, etc). You can store a file in the user home directory, but most operating systems have a designated location to store user data (e.g., 'Application Support' on Mac, AppData on Windows, etc). Plus the user probably won't appreciate you cluttering up their home directory. You can create a properties file and handle storing it in the proper place yourself, but an easier solution would be to use the Preferences API which abstracts the pain of having to know where to write the file.
Here is an example:
import java.util.prefs.Preferences;
public class Test {
public static final String DB_PROP = "user.selected.db.address";
public static void main(String[] args) {
Preferences prefs = Preferences.userNodeForPackage(Test.class);
prefs.put(DB_PROP, "foo");
String dbAddress = prefs.get(DB_PROP, null);
System.out.println(dbAddress);
}
}
Related
I have a Java project which comprises of the program named runProgram and configuration file named config.properties inside the package pack. I am trying to run the project as a .jar file from the command prompt in Windows 7. But I don't know how to indicate the specific configuration file that I want to use. I tried "open file" with the file name and it didn't work.
Program:
package pack;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class runProgram {
public static void main(String[] args){
double value;
Properties configFile = new Properties();
try {
configFile.load(helloworld.class.getClassLoader().getResourceAsStream(
"\\pack\\config.properties"));
} catch (IOException e) {
e.printStackTrace();
}
value = Double.parseDouble(configFile.getProperty("value"));
System.out.println("Value is: "+value);
}
}
Config File:
value = 75
I give it a shot, but I don't know if I'm getting your question correctly.
But I don't know how to indicate the specific configuration file that I want to use.
If this is about running the tool, while specifying another config file every time, I'd go with Apache CLI, to parse and handle command line arguments. Then the user can specify the file every time he/she is running your tool.
(Under 'usage' you can find some examples, but I'm not allowed to post more than two links right now)
But if you want to know more about handling java properties files, here's a good tutorial:
http://www.mkyong.com/java/java-properties-file-examples/
Also, for OS independent path definitions, have a look at System.getProperty("file.separator"), which, as the name says, tries to receive the OS specific path separator (e.g., '\' for Windows, '/' for UNIX systems).
Hope this helps.
As the title says, I have a PDF document which is stored locally and using Java I would like to open it on an arbitrary page. My question is much the same as this question, however the proposed solution seems rather hacky so I would prefer a more conventional answer if possible. I understand that the code shown below will not work because #page=5 should be appended to the URL in the browser and not the file path, however I'm really not sure what to try next. Any help would be much appreciated!
import java.io.File;
import java.io.IOException;
import java.net.URL;
public class OpenPdfTest {
public OpenPdfTest(){
try {
File myFile = new File("test.pdf");
URL url = myFile.toURI().toURL();
Process p = Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + url + "#page=5");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args){
new OpenPdfTest();
}
}
What about using http://tika.apache.org/ and read the whole file, convert it and use the part of the pdf File that you want. You can read in any File you want with Apache Tika. With this Lib you can open any kind of files, also pdf-Files and proceed them.
Take my Answer just as a first guess.
I'm making a game for a school assignment, one of the features is that the game can be saved and loaded. While in eclipse everything worked but after making it an executable jar it won't create the file at the specified location.
I am using this code to get it to save in the folder I want:
see below for full code
Note that the folders, quarto & savefiles, are created but the save file itself isn't.
I'm writing object to a .sav file using this code:
see below for full code
Does this have to do with permissions?
Edit: Ran it in cmd, no exceptions when i tried to save. Added a java.policy file to the folder the jar was in, no difference. I got a previously saved file and put it in the quarto/savefiles map because I wanted to see if it did load correctly (this also uses the user.home to get to the right folder). It loaded correctly. I also searched for the savename.sav to see if it saved it somewhere else, didn't find anything.
Full class:
package quarto;
import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class TaskSpelOpslaan extends SpelGegevens{
public static void runSpelOpslaan() {
String savename = SpelOpslaanScherm.getSaveName();
String userHome = System.getProperty("user.home") + File.separator + "quarto" + File.separator + "savefiles";
String locatie = userHome;
File folder = new File(locatie);
if (!folder.exists()) {
folder.mkdirs();
}
try{
if(!savename.contains(".sav"))
{
savename = (savename+".sav");
}
else
{
return;
}
FileOutputStream saveFile=new FileOutputStream(folder+File.separator + savename);
ObjectOutputStream save = new ObjectOutputStream(saveFile);
save.writeObject(bordInfo);
save.writeObject(stukGeplaatst);
save.writeObject(stukGeselecteerd);
save.writeObject(spelerBeurt);
save.writeObject(gekozenStuk);
save.writeObject(bordImage);
save.writeObject(stukImage);
save.writeObject(naamSpeler1);
save.writeObject(naamSpeler2);
save.close();
}
catch(Exception exc){
exc.printStackTrace();
}
}
}
EDIT2: I'm thankful for all your help, but I just realized a really stupid mistake i made... else{return;} didn't do what I taught it did and could be removed altogether.
Sorry for the trouble!
Is there anyway to mark this question closed or should i just let it sit?
Java programs (especially applets) tend to need permissions to do stuff like read and write files. That's why there are .policy files. Add a file called java.policy into the same dirrectory as the jar. In the file you have to grant permissions. So put this into the .policy file:
grant CodeBase "Example.jar"
{
permission java.security.AllPermission;
};
This will grant all the permissions for Example.jar.
I am working on a basic game similar to Break Out and I plan to use a text file to store level data on where various objects should be located when a level is rendered onto the screen. Here is the code:
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LevelData {
public LevelData(){
readFile();
}
public void readFile(){
try{
BufferedReader in = new BufferedReader(new FileReader("Levels"));
String str;
while((str = in.readLine()) != null){
process(str);
in.close();
}
}catch (IOException e){
System.out.println("File Does Not Exist");
}
}
private void process(String str){
System.out.println(str);
}
}
This following code, based off of previous research, should access the file "Levels" that is located in the same package as the Java class, but if the program cannot access the file then it should print "File Does Not Exist" to the console. I have created a file called "Levels" that is located in the same package as the Java class but whenever I run this class, it does not read the file properly and it catches the Exception.
Does anyone have any ideas on why it cannot access the proper file? I have already looked on various other threads and have found nothing so far that could help me.
Thanks in advance
Your Levels file probably doesn't want to be in the same package as the class, but rather, in the same directory from where your java program was run.
If you're using eclipse, this is probably the project directory.
Your issue is probably the lack of a file extension!
BufferedReader in = new BufferedReader(new FileReader("Levels.txt"));
In case you are running from Eclipse, the file should be accessed like new FileReader("src/<package>/Levels") .
Closing the inputstream in.close(); should happen outside the while loop.
As you said you plan to use a text file to store level data. One way to solve the problem is to provide relative path to the file while storing and while reading the file use the relative path to read the file. Please don't forget to specify the extention of the file.
I see a few problems, the first one being there's no file extension. Second, the in.close() is in the while loop, and since you are planning on storing high scores, I would recommend you would use an ArrayList.
It is always a good practice to specify the absolute path name of the file if the file is external to your jar file. If it is part of your jar file, then you need to get it using 'getResourceAsStream()'.
I am trying to make this program that will write a file to the users computer but am having trouble really, I want to write a file called desktop.bat that I have to the c:/ directory but it doesn't seem like it's working. this is the code:
package javawriter;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class JavaWriterObject {
public void TryThis(){
try{
File file = new File("C:\\Desktop.bat");
if (file.exists()){
System.out.println("The file exists \ndirectory is found");
}else{
System.out.println("file is not found yet ".concat("file will be created"));
file.createNewFile();
}
FileWriter out = new FileWriter(file);
BufferedWriter writer = new BufferedWriter(out);
writer.write();
writer.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
Do I have to write a String for the writer.write(); or can I do something where I can write the file I want instead?
Java 7's Files.copy method helps you copy a file from one location to another.
If you're using an older version of Java, you will need to either read the original file in yourself and copy its contents into your new file, or you'll have to use a third-party library. See the answers to this question for several good solutions, including using Apache Commons IO FileUtils or just the standard Java API.
Once you've decided how you want to copy the file, you might run into another problem. By default, Windows 7 will prevent you from writing to certain directories such as C:\. You can try writing to a different directory, such as in the temp directory or any location within the user's home directory. If you must write to C:\, the easiest solution (aside from creating the file ahead of time in Windows and overwriting it in your program, which probably defeats the purpose) is to disable UAC and make sure your user account has write permission on that directory--but this, of course, has security implications.
You have to get the content you want to write from somewhere, either a String literal in your application, or, the preferred method would be from a resource (bundled along with your application) via. YourClass.class.getResourceAsStream(name).
Copying an input stream to a file is a bit of effort, Guava can copy, but, if you're using Guava, you may as well copy directly from the resource to the file.