how to create a existing file in java - java

I am asking of there's a way how I could put like a program or a bat file or any file that has stuff written in it and them when he clicks on a button it will create that file that i have put into my project on to the users desktop is there a way?
File test = new File("C:/Users/"
+ System.getProperty("user.name")
+ "/AppData/Roaming/.minecraft/mods/welcome.txt");
try { test.createNewFile(); }
catch (IOException e1) { e1.printStackTrace(); }
this doesnt work.

If the file you want to creating is already exist in the disk, then you can print a message like the "File already exists" -
try {
File file = new File("c:\\some\location\file_name.txt");
if (file.createNewFile()){
System.out.println("File is created!");
}else{
System.out.println("File already exists.");
}
}catch (IOException e) {
e.printStackTrace();
}

In order to just put a file on an other computer you will need to be granted permission in some way to do that (otherwise anyone could just infect any networked computer with any content they desired). There are several ways you could gain access to an other computer (look into virtual private network and mapped network drive). The most common way of delivering files to another computer is to set up a web site where the user can request the file to be downloaded to their machine by clicking on a link. You could also write a client program that used an http get to allow the client user to request content be downloaded to a specific place on their machine.

ok i found out how i just downloaded the files from a server that i have "made"

Related

How to rename a file using a java while it is open

In my java code, I am using renameTo method to rename the file. I am able to do it successfully if the file is closed physically. But I am unable to do so if the file I am trying to rename is open.
How do I close the file thru code?
This is the code :
File file = new File("/users/abc.txt");
File newFile = new File("/users/xyz.txt");
if (file.renameTo(newFile)) {
System.out.println("File rename success");
} else {
System.out.println("File rename failed");
}
Thanks in advance.
You cannot close a file in Java that is opened by another user. It is highly platform dependant, it is impossible if that user/process has higher priviledges then your process, and the user editing it might hava data loss, if he is in the process of editing that file in an Editor. Don't ever do that.
The only way would be to wait until the file has been closed by that other user like that, however, I still discourage from doing so. If you have to use that file, just exit your application with an error.
File file = new File("/users/abc.txt");
File newFile = new File("/users/xyz.txt");
try {
while (!file.renameTo(newFile)) {
Thread.sleep(10_000); // wait 10 seconds
}
} catch (InterruptedException ex) {
// ignore
}

How to get my page to update an image when overwritten

I am attempting to overwrite and update an image on a page whenever my end user would like. They would simply upload a new image, and it will replace the old with the same file name and then the src path in the web page does not need to change. However, it kind of works. The file overwrites. but when I refresh the page the image does not change to the new. The odd kicker is, When I go into my IDE (Eclipse) and double-click the new image file, THEN I can refresh the web page and it shows the new replaced one. This is my first job project, and I have not found the answer elsewhere.I will provide the code;
<img th:src="#{/img/uploadedFile.jpg}" alt="image"></img>
#RequestMapping(method=RequestMethod.POST, value="image")
public String processImageForm(#RequestParam("file") MultipartFile file,
RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:image";
}
String extension = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
Path path = Paths.get(UPLOADED_FOLDER + fileName + extension);
try {
Files.deleteIfExists(path);
} catch (IOException | SecurityException e) {
System.err.println(e);
}
try {
// Get the file and save it somewhere
byte[] bytes = file.getBytes();
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:image";
}
}
My guess would be that you are not copying that file to the correct location.
You know that in a web app the the war file is created and then deployed on a server. So in order to change something you need to change it on the server (even when running from Eclipse it creates a server context from you). I guess that's where your problem comes from - you copy the file to the wrong place.
And when you are running from Eclipse the file is properly replaced on your local file system but this doesn't change the deployed war application. When you double click it in Eclipse it notices the change and automatically redeploys it for you basically changing the file on the server.

Can't Find Created File - Needs Root Privileges?

My app downloads a file to my Android tablet. I can see the file on my tablet, but I can't find the file using my computer's file manager.
A response to another Stack Overflow question says the file manager may need "root privileges," but I don't know how to give a file manager root privileges or download a file manager that has root privileges. Is that possible? A second answer to that same question mentions some way to transfer the file using the command line, but I haven't been able to figure out how to do that.
I need to be able to transfer the file to my computer. What is the easiest way to do this?
void newFile() {
try {
File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), "file.txt");
FileOutputStream fos = new FileOutputStream(file);
String myInputText = "I really hope this works!";
fos.write(myInputText.getBytes());
fos.close();
System.out.println("My file is at " + file.getAbsolutePath());
} catch (IOException e) {
e.printStackTrace();
}
}
If you familiar with Linux Operating system, that you can use command line to chmod the file privilege. But I think if you can move this file in your tablet, maybe try to transfer it by Blue tooth, email is much easier.

Android file is hidden on external storage

I am writing out a file to the external storage on android. The file shows up in my device when I browse to location using the ap ES file explorer.
But when I plug my device in to windows, the file does not show up.
Furthermore if I write an empty file named "test.wav" to Ringtones folder, no test.wav will show up in my ringtones settings.
But, if I create an empty file in windows named "test.wav", and drag and drop into my Ringtones folder, it will then properly show up in my ringtones browser in settings.
Code I am using is a follows.
File file = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_RINGTONES), "testfile.wav");
file.setReadable(true);
try {
FileOutputStream fileOut = new FileOutputStream(file);
stream = new DataOutputStream(fileOut);
stream.flush();
stream.close();
//this code successfully creates a file
// but file is not viewable by all means
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Android uses tables to keep track of images, videos, sounds and so on these tables called " content providers " for example it uses MediaStore.Images.Media.DATA for images Note that these tables are used for the view this illustrates why you can only see it using ES. When you add new file manually, you need to add an entry for this file in the corresponding table or refresh your music library in case of sound file was added, but when you add file using windows the device's driver updates its tables automatically. Try refreshing your music application or even restarting your phone if this solves the problem updating your content provider is the solution.
I could be wrong but I think that it is /extsd showing when you plug your device into Windows, whereas external storage is actually /sdcard. so your file is in /sdcard, not in /extsd, that's why you don't see it. At least whenever I plugged Android tab into Windows, I could only browse its removable SD, i.e. /extsd but I couldn't see /sdcard

Comment enabled PDF

I have written a java program which enabled the shared review feature on a pdf. After making the pdf as Shared Review PDF it sends the pdf to a link folder in UNIX machine (link folder means shortcut path of a folder). After that an shell script, which runs differently via crontab makes the pdf as comment enabled and via the script that pdf is copied to some folder.
Now the question is whenever I am copying the file in the UNIX link folder (for copying the file to the link folder I am using FileUtils.copyInputStream() function.), a comment enabled script is executing and doing all comment enabled things in pdf(.sh script in UNIX which runs not from my program.) but during saving the file it prompts the file is readonly and exits without saving the file. But if I do the same thing (putting the file manually to the link folder in UNIX) manually it makes the pdf file as Comment enabled. This is my sample code which sends the file to a folder.
try{
String outFname="SR_"+fname;
srEnabledIs = new FileInputStream(pdfoutputPath+fname);
if(srEnabledIs!=null && !path.equals("")){
Date today = new Date();
SimpleDateFormat format = new SimpleDateFormat("dd_MM_yyyy_hh_mm_ss_a");
String timeStamp=format.format(today);
FileUtils.copyInputStreamToFile(srEnabledIs, new File(path+outFname));
logtracker.writeDebugNormalLog("AnnotationMain","file copied to " + path);
try{
lrfile.renameTo(new File(pdfinputPath+"/pdf/"+fname.split("[.]")[0]+"_"+timeStamp+".pdf"));
}catch(Exception ex){
logtracker.writeDebugNormalLog("AnnotationMain", ex.getMessage());
ex.printStackTrace();
}
}else{
if(path.equals("")){
logtracker.writeDebugNormalLog("AnnotationMain", "File not copied as path not found.");
}
if(srEnabledIs==null){
logtracker.writeDebugNormalLog("AnnotationMain", "File not copied as InputStream is null.");
}
if(srEnabledIs==null && path.equals("")){
logtracker.writeDebugNormalLog("AnnotationMain", "File not copied as InputStream is null and path not found.");
}
}
}catch(IOException e){
logtracker.writeDebugNormalLog("AnnotationMain", e.getMessage());
e.printStackTrace();
}finally{
if(srEnabledIs!=null){
srEnabledIs.close();
}
}
But the same program is running and executing successfully in other UNIX machine. I am really unable to understand the situation. Please help me out of this situation.

Categories