I want to rename a file name xxx.docx to xxx.docx.zip then rename it back to xxx.docx in Java.
Here is my code.
File file = new File(path);
File file2 = new File(path+".zip");
file.renameTo(file2);
File file3 = new File(file.getPath());
file2.renameTo(file3);
It won't work. Thank you.
Edit : The problem is I forgot to close the doc before renaming it.
The code like that works. Most probably some other process has locked the file and made it read only. You have either opened it in word (since it is docx file) or something like that. Maybe it is in a readonly location.
The code is working though. Try with different file and you will see it is fine (I tried it).
Related
I've been trying to set up a Scanner to use a File as an input, but it doesn't seem to recognize the filepath. The file exists in the same folder as my .java files.
File errorList = new File("Errors.txt");
Scanner errorIn = new Scanner(errorList);
This results in a FileNotFoundException.
What am I doing wrong, and how can I fix this?
One other approach you could try is, execute the below code in your eclipse (from any of your class), and see where the hello.txt is created, so you get an idea of where Java is looking for the file.
new File("hello.txt").createNewFile();
Then you could either put your Errors.txt in that location or provide the corresponding relative location.
I'm making a game that saves information into a binary file so that I can start at the point I left the game on the next use.
My problem is that it works fine on my PC because I chose a path that already existed to save the file, but once I run the game on another PC, I got an error saying the path of the file is invalid (because i doesn't exist yet, obviously).
Basically I'm using the File class to create the file and then the ObjectOutputStream and ObjectInputStream to read/write info.
Sorry for the noob question, I'm still pretty new to using files.
You must first check if the directory exists and if it does not exist then you must create it.
String folderPath = System.getProperty("user.home") + System.getProperty("file.separator") + "MyFolder";
File folder = new File(folderPath);
if(!folder.exists())
{
folder.mkdirs();
}
File saveFile = new File(folderPath, "fileName.ext");
Please note that the mkdirs() method is more useful in this case instead of the mkdir() method as it will create all non existing parent folders.
Hope this helps. Good luck and have fun programming!
Cheers,
Lofty
You are looking for File mkdirs()
Which will create all the directories necessary that are named in your path.
For example:
File dirs= new File("/this/path/does/not/exist/yet");
dirs.mkdir();
File file = new File(dirs, "myFile.txt");
Take in consideration that it may fail, due to proper file permissions.
My solution has been create a subdirectory within the user's home directory (System.getProperty("user.home")), like
File f = new File(System.getProperty("user.home") + "/CtrlAltDelData");
f.mkdir();
File mySaveFile = new File (f, "save1.txt");
I try to write a text to a file and read this text later. When I use FileWriter I become a NullPointerException?
Is that a permission problem or ...? I also try the PrintWriter but I see the same Exception
.
This my code:
FileWriter fw = new FileWriter(new File("file.file"));
fw.write("XYZ");
best regards
londi
I guess your problem is that you use a relative file path, but that the origin of the relative path is not the one you think.
First of all, try to use an absolute path, that would be, on linux-like machines something like /home/me/myCode/myfile.txt or on windows something like c:/some/path/myfile.txt
Another thing you can do, in order to know what happens is print the origin.
File origin = new File(".");
System.out.println(origin.getAbsolutePath());
Once you know where the origin is, you can see what you need in order to get to your file.
Hope it will help.
Sounds like a permission issue. On iOS your application lives within a security sandbox, so you cannot just randomly read and write files anywhere you want. You could either use File.createTempFile to create a temp file somewhere hidden you your sandbox where nothing else can see it, or use the native api to determine where to dump your files. The following example will give you a file reference to the Documents Directory folder:
NSArray nsa = NSFileManager.defaultManager().URLsForDirectory$inDomains$(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask);
NSURL nsu = (NSURL)nsa.getFirst();
String snsu = nsu.getAbsoluteString() + "MyNewDocument.pdf";
File newFile = new File(new URI(snsu));
I made a small game that requires to play background music on it, I have images, a txt file and an audio file, they all work after exporting the JAR except for the audio file.
here is the code I used to import :
The Images :
(new ImageIcon(getClass().getResource("/data/131868.jpg"))
The Text file :
BufferedReader br = new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/data/dictionnaire.txt")));
The Audio file ( I included also the code to play it that I found while searching) :
File f =new File(Main.class.getResource("/data/gmu.mp3").getFile());
final Player p=Manager.createRealizedPlayer(f.toURI().toURL());
p.start();
while(true){
if(p.getMediaTime().getSeconds()==p.getDuration().getSeconds()){
p.stop();
p.setMediaTime(new Time(0));
p.start();
}
}
Basically the File Object was : File f = new File("/data/gmu.mp3") I just added modifications to make it look like the others ...
It did work in Eclipse, but not JAR.
You'd better know that: File is just the name of the file, not the file itself. Like the house number, it tells you the house's location, but is doesn't represent the house.
So, you can use it like this:
InputStream is = this.getClass().getResourceAsStream("/data/gmu.mp3");
File fi = new File(is);
Tell me the result:)
Solution
Try placing the gmu.mp3 inside the source before exporting the jar.
Why?
When you export a jar, it wraps all the fun code up that is inside the source folder. File f = new File("/data/gmu.mp3") simply points the program to that file names gmu.mp3 in the file system. If you place the gmu.mp3 inside the source folder and update the File constructor to reflect the new location, the mp3 should get wrapped up into the jar along with all the code.
Let me know how it goes -Scott
A java.io.File represents a jar-ed file as "ThePacked.jar!/path/inside/file.mp3", which makes problem when used as a File.
To read a jar-ed file's content, you can read from an InputStream given by getResourceAsStream(String filename).
or
To use the file as a real java.io.File, (what I did is to) read it from the InputStream and copy it to a location outside the jar (eg. to a temprary file).
a simple question, I have the following java code:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
System.out.println(file.length());
If I run it, I see that the file has changed of name correctly, but strangely file.length() returns 0 (And the file is not empty)
Any idea?
Thank you
File is immutable. It will always point to the filepath you created it with.
So when you rename your file, the file to which your File object points doesn't exist anymore (it was renamed) and you get the file length of 0.
See also the javadoc.
Try this:
File file = new File("myFile.xls");
file.renameTo("mySecondFile.xls");
File file2 = new File("mySecondFile.xls");
System.out.println(file2.length());