First of all, i found some answers about my problem but did not help.
Here's one: Does Windows cache the contents of .url (Internet Shortcut) files?
I have an application that remove the actual shortcuts and create new ones:
for (String shortcut : shortcuts) {
File f = new File(shortcut + ".url");
if (f.exists()) {
f.delete();
}
try {
FileWriter fw = new FileWriter(shortcut + ".url");
fw.write("[InternetShortcut]\n");
fw.write("URL=http://localhost:" + port + "/" + shortcut + "\n");
fw.flush();
fw.close();
} catch (IOException e) {
}
}
This is the result:
[InternetShortcut]
URL=http://localhost:8889/app
And it's fine, but when i change the port and create another shortcut, windows keeps opening the old url.
In the file properties i can see the right url in the details tab, but in the document of web tab still showing the old url.
As default i'm using Chrome, when i drag the .url file to the browser it work and load the right url, but if i double click loads the old url.
Thanks.
Related
I'm writing this post because I need some help.
I'm having trouble display an image depending on a specific path in my App.
Basically what it's doing: I have a module named Sector, and each Sector can have an image related to it. When I use the Upload component of Vaadin, I save the path of the image to a table in my database so that it can display the picture chosen before.
The actual path of the image is weird, it seems that Vaadin copies the image to a dynamic random folder. It seems logical that it can't use the actual path of the image.
But here's the problem: The path is well entered in the Database, but when I reload the page (F5), Vaadin can't shows the image anymore. Which upsets me since it should display it well.
The path that Vaadin creates with the uploaded image : VAADIN/dynamic/resource/2/c1ef7b9d-8f2b-4354-a97e-fe1fd4e868e7/551434.jpg
I can put some code if it can help.
The screenshots show what it's doing once I'm refreshing the browser page.
The image is being uploaded
After refreshing the page
Here is the part of the code where I handle the upload image:
upload.addSucceededListener(e -> {
Component component = createComponent(e.getMIMEType(),
e.getFileName(), buffer.getInputStream());
showOutput(e.getFileName(), component, output);
//imgUpload = (Image) component;
InputStream inputStream = buffer.getInputStream();
targetFile = new File(PATH + currentProjetId + "\\secteur" + currentSecId + "\\photoSec.png");
try {
FileUtils.copyInputStreamToFile(inputStream, targetFile);
} catch (IOException e1) {
e1.printStackTrace();
Notification.show("Error");
}
System.out.println("PATH : " + targetFile.getPath());
});
I think you are using an in-memory resource that's discarded when you refresh the view. You have to take the contents of the file and save it in a file inside a directory in the server's file system. Here's an example:
FileBuffer receiver = new FileBuffer();
Upload upload = new Upload(receiver);
upload.setAcceptedFileTypes("text/plain");
upload.addSucceededListener(event -> {
try {
InputStream in = receiver.getInputStream();
File tempFile = receiver.getFileData().getFile();
File destFile = new File("/some/directory/" + event.getFileName());
FileUtils.moveFile(tempFile, destFile);
} catch (IOException e) {
e.printStackTrace();
Notification.show("Error").
}
});
Currently I have a code where I retrieve the website plain text and store it inside a text file. I managed to do that but when I want to enter a new line in the text file it doesn't work.
My result
This is the article titleThis is the starting of the first paragraph
What I want
This is the article title
This the starting of the first paragraph
My source code
public void storeHTML(Context context, ArrayList<String> storeHTML, String address) {
try {
File root = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+ "/voicethenews");
if (!root.exists()) {
root.mkdirs();
}
address = address.substring(address.lastIndexOf("/") + 1);
File gpxfile = new File(root, address + ".txt");
FileWriter writer = new FileWriter(gpxfile);
//FileOutputStream fileOutputStream = new FileOutputStream(gpxfile);
//BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
for(int i = 0; i < storeHTML.size(); i++) {
//bufferedWriter.write(storeHTML.get(i));
//bufferedWriter.newLine();
writer.append(storeHTML.get(i) + System.lineSeparator());
}
writer.flush();
writer.close();
Toast.makeText(context, "Saved", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
}
I've tried multiple code and solution but it's still not working.
I found the actual reason why it doesn't display as I intended.
The reason why it doesn't seem to work in the first place it was due to me opening the text file using the default notepad. When open using other text editor such as notepad++, the output in the text file was writen as intended.
If you get detail from HTML. So, let use <br>, instead of <br \>
This is an example code to add text to a textView b
b.setText(Html.fromHtml("<b>" + st + "</b>" + "<br/>" + cursor.getString(1)));
Reference: How do i add a new line in html format in android?
This question is probably addressing the exact same issue you are having:
System.lineSeparator() doesn't exist in android
There was a bug in the pre 1.7 SDKs where you would have to call the environmental variable directly.
My goal is to move a file from one directory to another. The source is on a local drive and the destination is on a network drive. It doesn't matter whether I move or I copy then delete source. The file is approx 6GB.
What I've tried:
// C:\path\to\dir\file.bak
File source = new File(localRoot + backup);
// \\192.168.1.100\path\to\dir\file.bak
File dest = new File(storageRoot + "/" + storagePath + "/" + backup);
try {
log("Copying");
// I've tried copyFile as well.
FileUtils.copyFileToDirectory(source, dest);
log("copied");
} catch (Exception e) {
e.printStackTrace();
}
File source = new File(localRoot + backup);
File dest = new File(storageRoot + "/" + storagePath + "/" + backup);
try {
log("Copying");
// I've tried move and creating Paths instead of Files as well.
Files.copy(source.toPath(), dest.toPath());
log("copied")
} catch (Exception e) {
e.printStackTrace();
}
I've tried as well a manual method using Input, OutputStreams and reading bytes.
The results is that a file is created in the destination with the correct filename with 0 bytes, and the source file is rewritten from 6GB to 0 bytes. This happens for all methods I've tried, the only exception is that when I tried move, the source file was deleted rather than rewritten.
All code is in early development, please refrain from commenting on best practices.
Thank you, and what am I missing or what else can I try?
I'm trying to create a Windows installer out of a jar file. Everything has been successful till the final stages.
I used launch4j to wrap the jar file into an exe file then used both, Advanced-Installer and Inno-Setup to create MSI folders. They both work, however, on some computers the exe file that is extracted does not close and can only be killed by using the Task Manager.
In my Java file, I handle the exit process (finally using System.exit(0)) because I would like to ask the user if they wish to save the file before exiting.
This is my code:
exitListener = new ExitListener();
theMainFrame.addWindowListener(new WindowAdapter() {
#Override
public void windowClosing(WindowEvent e) {
ProgramLog.logException(Level.SEVERE, "Problem...WindowsClosing method", new Exception());
exitListener.actionPerformed(null);
}
});
The logger works fine while it's a jar (creates a file and gives an exception), works fine while it's an exe but once I wrap it into an MSI, once opened it does not close and I do not see anything being logged which means it isn't reaching the windowClosing event.
I have tried the exe file by itself on two Windows computers and it works fine (saving and exiting); but once extracted from the installer, it does not quit.
Any suggestions appreciated.
EDIT
So thanks to MadProgrammer I figured out the problem was with the logger itself. Will be editing my code and update depending on how it works out
SOLUTION
So thanks to MadProgrammer, I found out the problem was with the Logger's saving location and not some Windows machine just didn't quit executable files. I have changed the location from the ProgramFiles folder to {user.home}\AppData\Local{Program company}{Program name}
My previous code for the logger was
public ProgramLog() {
try {
FileHandler handler = new FileHandler(logFile);
logger = Logger.getLogger("com.program.msgs");
logger.addHandler(handler);
} catch (Exception e) {
}
}
I have edited it to
public ProgramLog() {
try {
String path = System.getProperty("user.home") + File.separator
+ "AppData" + File.separator + "Local" + File.separator
+ "CompanyName" + File.separator + "CompanyProduct" + File.separator;
File f = new File(path);
f.mkdirs();
FileHandler handler = new FileHandler(path + logFile);
logger = Logger.getLogger("com.program.msgs");
logger.addHandler(handler);
} catch (Exception e) {
}
}
Now my executable works after wrapping it into an MSI!!
I have a simple updater for my application. In code i am downloading a new version, deleting old version and renaming new version to old.
It works fine on Linux. But doesn't work on Windows. There are no excepions or something else.
p.s. RemotePlayer.jar it is currently runned application.
UPDATED:
Doesn't work - it means that after file.delete() and file.renameTo(...) file still alive.
I use sun java 7. (because I use JavaFX).
p.s. Sorry for my English.
public void checkUpdate(){
new Thread(new Runnable() {
#Override
public void run() {
System.err.println("Start of checking for update.");
StringBuilder url = new StringBuilder();
url.append(NetworkManager.SERVER_URL).append("/torock/getlastversionsize");
File curJarFile = null;
File newJarFile = null;
try {
curJarFile = new File(new File(".").getCanonicalPath() + "/Player/RemotePlayer.jar");
newJarFile = new File(new File(".").getCanonicalPath() + "/Player/RemotePlayerTemp.jar");
if (newJarFile.exists()){
newJarFile.delete();
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
System.err.println("Cannot find curr Jar file");
return;
}
if (curJarFile.exists()){
setAccesToFile(curJarFile);
try {
String resp = NetworkManager.makeGetRequest(url.toString());
JSONObject jsresp = new JSONObject(resp);
if (jsresp.getString("st").equals("ok")){
if (jsresp.getInt("size") != curJarFile.length()){
System.out.println("New version available, downloading started.");
StringBuilder downloadURL = new StringBuilder();
downloadURL.append(NetworkManager.SERVER_URL).append("/torock/getlatestversion");
if (NetworkManager.downLoadFile(downloadURL.toString(), newJarFile)){
if (jsresp.getString("md5").equals(Tools.md5File(newJarFile))){
setAccesToFile(newJarFile);
System.err.println("Deleting old version. File = " + curJarFile.getCanonicalPath());
boolean b = false;
if (curJarFile.canWrite() && curJarFile.canRead()){
curJarFile.delete();
}else System.err.println("Cannot delete cur file, doesn't have permission");
System.err.println("Installing new version. new File = " + newJarFile.getCanonicalPath());
if (curJarFile.canWrite() && curJarFile.canRead()){
newJarFile.renameTo(curJarFile);
b = true;
}else System.err.println("Cannot rename new file, doesn't have permission");
System.err.println("last version has been installed. new File = " + newJarFile.getCanonicalPath());
if (b){
Platform.runLater(new Runnable() {
#Override
public void run() {
JOptionPane.showMessageDialog(null, String.format("Внимание, %s", "Установлена новая версия, перезапустите приложение" + "", "Внимание", JOptionPane.ERROR_MESSAGE));
}
});
}
}else System.err.println("Downloading file failed, md5 doesn't match.");
}
} else System.err.println("You use latest version of application");
}
}catch (Exception e){
e.printStackTrace();
System.err.println("Cannot check new version.");
}
}else {
System.err.println("Current jar file not found");
}
}
}).start();
}
private void setAccesToFile(File f){
f.setReadable(true, false);
f.setExecutable(true, false);
f.setWritable(true, false);
}
I found the solution to this problem. The problem of deletion occurred in my case because-:
File f1=new File("temp.txt");
RandomAccessFile raf=new RandomAccessFile(f1,"rw");
f1.delete();//The file will not get deleted because raf is open on the file to be deleted
But if I close RandomAccessFile before calling delete then I am able to delete the file.
File f1=new File("temp.txt");
RandomAccessFile raf=new RandomAccessFile(f1,"rw");
raf.close();
f1.delete();//Now the file will get deleted
So we must check before calling delete weather any object such as FileInputStream, RandomAccessFile is open on that file or not. If yes then we must close that object before calling delete on that file.
windows locks files that are currently in use. you cannot delete them. on windows, you cannot delete a jar file which your application is currently using.
Since you are using Java 7, try java.nio.file.Files.delete(file.toPath()), it'll throw exception if deletion fails.
There are several reasons:
Whether you have permissions to edit the file in windows.
The file is in use or not.
The path is right or not.
I don't know wich version of Java you are using.
I know when Java was sun property they publish that the Object File can't delete files correctly on windows plateform (sorry I don't find the reference no more).
The tricks you can do is to test the plateform directly. When you are on linux just use the classic File object.
On windows launch a command system to ask windows to delete the file you want.
Runtime.getRuntime().exec(String command);
I just want to make one comment. I learned that you can delete files in Java from eclipse if you run eclipse program as Administrator. I.e. when you right click on the IDE Icon (Eclipse or any other IDE) and select Run as Administrator, Windows lets you delete the file.
I hope this helps. It helped me.
Cordially,
Fernando