Create shortcut to .jar using java-code - java

I wrote an updater for my Java application which downloads its newest jar-file online, replaces the shortcut to it before starting the new jar and finally deleting itself.
I used the following code to create the shortcut:
try {
//Location of shortcut -> Working
String address = "C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\App.lnk";
//Delete old shortcut -> Not working
File f = new File(address);
f.delete();
//Create new shortcut
FileWriter fw = new FileWriter(address);
fw.write("[Program]\n"); //Probably wrong section but cannot find real one
fw.write("FILE=" + (new File(App.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getPath()) + "App-"+version+".jar\n"); //Shortcut to newest version
fw.flush();
fw.close();
} catch (URISyntaxException e) {e.printStackTrace();}
The code does create a file but it seems to be broken so my question is what am I doing wrong here?

This is how it works:
ShellLink shortcut = ShellLink.createLink("App.jar").setWorkingDir(new File(".").getAbsolutePath());
shortcut.getHeader().getLinkFlags().setAllowLinkToLink();
shortcut.saveTo("C:\\Users\\"+System.getProperty("user.name")+"\\Desktop\\App.lnk");

Related

Writing to a JSON file with Java doesn't work after export

When I use my program within Eclipse everything works flawlessly, the JSON file is saved between launches. The problem occurs when i export the project to a Runnable Jar File, the saving of the JSON file no longer works, at all. I can still read from the file, but it doesn't save it.
Here is the "writing/saving" code I've written.
/*
* Write to character JSON file
*/
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
Since outside Eclipse neither the bin nor the file itself haven't been created yet, you have to create it, at first and if there was a file before, since we want to overwrite it, we use the delete method before creating it. So the whole changes are written here:
public void saveCharacterInfo() {
JSONObject obj = JSONUtils.getJSONObjectFromFile("/character.json");
obj.put("day", c.getDay());
obj.put("name", c.getCharName());
obj.put("hp", c.getCharHp());
obj.put("maxHp", c.getCharHpMax());
obj.put("armor", c.getCharArmor());
obj.put("speed", c.getCharSpeed());
obj.put("strength", c.getCharStrength());
obj.put("money", c.getCharMoney());
obj.put("food", c.getCharFood());
obj.put("maxFood", c.getCharMaxFood());
obj.put("morale", c.getCharMorale());
obj.put("bait", c.getCharBait());
try {
URL resourceUrl = getClass().getResource("/character.json");
File file = new File(resourceUrl.toURI());
file.getParentFile().mkdirs();
file.delete();
file.createNewFile();
FileWriter writer = new FileWriter(file);
writer.write(obj.toString());
writer.flush();
writer.close();
} catch (Exception e) {
}
}
I tested it and the way to make the jar to create new folders is to execute it from the windows command console with:
java -jar jarName.jar
Or to create a bat file on the same folder.

File not created in Java (Eclipse)

So I've been doing like the simplest thing ever. Create a text file for a Java application. Just directly in the C directory:
File file = new File("C://function.txt");
System.out.println(file.exists());
The file never shows up though, I changed the slashes, changed the path, nothing. Could anyone help me out here?
There are many methods to create a new file with java : (You should firstly verify the permission to create a file in that folder c: )
String path = "C:"+File.separator"function.txt";
File f = new File(path);
f.mkdirs();
f.createNewFile();
__ or
try {
//What ever the file path is.
File f = new File("C:/function.txt");
FileOutputStream is = new FileOutputStream(f);
OutputStreamWriter osw = new OutputStreamWriter(is);
Writer w = new BufferedWriter(osw);
w.write("Line 1!!");
w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file function.txt");
}
After Java 7, you should use the new I/O API instead of the File class to create new files.
Here is an example:
Path path = Paths.get("C://function.txt");
try {
Files.createFile(path);
System.out.println(Files.exists(path));
} catch (IOException e) {
e.printStackTrace();
}
You are just creating a File object, not a file itself. So in-order to create new file you need use below command:
file .createNewFile();
This would create your file under C:\ drive. Maybe you can also check if it is already exsits and handle exception etc.
If the file is not exist you can create a new file like:
if(!file.exists()) {
try {
file.createNewFile();
System.out.println("Created a new File");
} catch (IOException e) {
e.printStackTrace();
}
}
The simplest way to do this:
String path = "C:"+File.separator+"function.txt";
File file = new File(path);
System.out.println(file.exists());
try this:
File file = new File("C://function.txt");
if (!file.isFile())
file.createNewFile();
Try this
File file = new File("C:/test.text");
f.createNewFile();

How to move specific files from one folder to another using java

I have tried and succeed moving files from one folder to another folder using java . Here is my code
File source = new File("D:\\polo\\");
File desc = new File("E:\\polo2\\");
try {
FileUtils.copyDirectory(source, desc);
} catch (IOException e) {
e.printStackTrace();
}
But i would like to move specific files from one folder to the other not all the files. Is this possible to do in java. Please help us on this
You can use Java SE standard utility
java.nio.file.Files.copy(Path source, Path target, CopyOption... options)
use renameTo
public static void main(String[] args)
{
try{
File source = new File("D:\\polo\\");
File desc = new File("E:\\polo2\\");
if(source .renameTo(new File("E:\\polo2\\" + afile.getName()))){
System.out.println("File is moved successful!");
}else{
System.out.println("File is failed to move!");
}
}catch(Exception e){
e.printStackTrace();
}
}
In java 1.7, new IO classes were added, including the Files utility class which has a method copy.
There is an example of usage here.
Use IOUtils Library for copy file from one location to another location.
For eg.
File source = new File("D:\\polo\\fileold");
File desc = new File("E:\\polo2\\filenew");
IOUtils.copy(source, desc);
Try this..

FileNotFoundException when using FileWriter

I am trying to write some message to text file. The text file is in the server path. I am able to read content from that file. But i am unable to write content to that file. I am getting FileNotFoundException: \wastServer\apps\LogPath\message.txt (Access Denied).
Note: File has a read and write permissions.
But where i am doing wrong. Please find my code below.
Code:
String FilePath = "\\\\wastServer\\apps\\LogPath\\message.txt";
try {
File fo = new File(FilePath);
FileWriter fw=new FileWriter(fo);
BufferedWriter bw=new BufferedWriter(fw);
bw.write("Hello World");
bw.flush();
bw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Please help me on this?
Please check whether you can access the apps and LogPath directory.
Type these on Run (Windows Key + R)
\\\\wastServer\\apps\\
\\\\wastServer\\apps\\LogPath\\
And see whether you can access those directories from the machine and user you are executing the above code.
You don't have write access to the share, one of the directories, or the file itself. Possibly the file is already open.
After this line
File fo = new File(FilePath);
try to print the absolute path
System.out.println( fo.getAbsolutePath() );
And then check whether the file exists in that location, instead of directly checking at
\\\\wastServer\\apps\\LogPath\\message.txt
So , you will know, where the compiler is searching for the file.

Overwriting txt file in java

The code I've written is supposed to overwrite over the contents of the selected text file, but it's appending it. What am I doing wrong exactly?
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
f2 = new FileWriter(fnew,false);
f2.write(source);
/*for (int i=0; i<source.length();i++)
{
if(source.charAt(i)=='\n')
f2.append(System.getProperty("line.separator"));
f2.append(source.charAt(i));
}*/
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EDIT
I tried making a new temp.txt file and writing the new contents into that, deleting this text file and renaming temp.txt to this one. Thing is, the deletion is always unsuccessful. I don't think I have to change user permissions for this do I?
Also, a part of my program lists all the files in this directory, so I'm guessing they're being used by the program and so can't be deleted. But why not overwritten?
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold=new File("../playlist/"+existingPlaylist.getText()+".txt");
fold.delete();
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Your code works fine for me. It replaced the text in the file as expected and didn't append.
If you wanted to append, you set the second parameter in
new FileWriter(fnew,false);
to true;
SOLVED
My biggest "D'oh" moment! I've been compiling it on Eclipse rather than cmd which was where I was executing it. So my newly compiled classes went to the bin folder and the compiled class file via command prompt remained the same in my src folder. I recompiled with my new code and it works like a charm.
File fold = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fold.delete();
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
String source = textArea.getText();
System.out.println(source);
try {
FileWriter f2 = new FileWriter(fnew, false);
f2.write(source);
f2.close();
} catch (IOException e) {
e.printStackTrace();
}
Add one more line after initializing file object
File fnew = new File("../playlist/" + existingPlaylist.getText() + ".txt");
fnew.createNewFile();
This simplifies it a bit and it behaves as you want it.
FileWriter f = new FileWriter("../playlist/"+existingPlaylist.getText()+".txt");
try {
f.write(source);
...
} catch(...) {
} finally {
//close it here
}
The easiest way to overwrite a text file is to use a public static field.
this will overwrite the file every time because your only using false the
first time through.`
public static boolean appendFile;
Use it to allow only one time through the write sequence for the append field
of the write code to be false.
// use your field before processing the write code
appendFile = False;
File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;
try {
//change this line to read this
// f2 = new FileWriter(fnew,false);
// to read this
f2 = new FileWriter(fnew,appendFile); // important part
f2.write(source);
// change field back to true so the rest of the new data will
// append to the new file.
appendFile = true;
f2.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

Categories