deleting a file with a java file - java

Path to = Paths.get("C:\\submissions\\SOFT222\\Assessment1\\10403435\\Submission15\\OO Java Bootcamp - Java and NetBeans - Copy\\test\\oojavabootcamp\\OOJavaBootcampTestMasase - Copy");
Path from = Paths.get("C:\\submissions\\SOFT222\\Assessment1\\OOJavaBootcampTest - Copy");
void Paths() throws IOException {
File submissionFolder = new File("C:\\submissions\\SOFT222\\Assessment1\\10403435\\Submission15\\OO Java Bootcamp - Java and NetBeans - Copy");
if (submissionFolder.exists()) {
System.out.println("Folder exists");
try {
// Remove test files
Files.deleteIfExists(Paths.get(to + ".java"));
Files.copy(Paths.get(from + ".java"), Paths.get(to + ".java"));
} catch (IOException ex) {
System.out.println("Original file copy did not work.");
}
}
}
This code deletes the .java file but doesn't seem to copy the .java file(OOJavaBootcampTest - Copy) to the 'to' variable cos the name remains the same after deletion has occurred. I think its deleting it and making a copy of it instead of replacing it with the .java in from variable. Please what am I doing wrong

You don't tell what the path is which raises the error, so it's hard to tell.
Note that you can:
Files.deleteIfExists(somePath);
so you may want to use this instead.
It's hard to tell what you really want so here I'll just assume that you want to overwrite to with from; in this case, do:
final Path parentDir = to.getParent();
Files.createDirectories(parentDir);
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTING);

Related

FileNotFoundException even though the file is there?

I am trying to copy and paste a Minecraft World from a template into the server folder and then load the world. I am getting this error:
java.io.FileNotFoundException:
.\C:\Users\Archie\Desktop\Server.b571c7a6-3297-48eb-ac24-1bac65ef9727\session.lock
(The filename, directory name, or volume label syntax is incorrect)
So here is what I tried:
Printing out the source of the path and then the place I am copying it to, to console to check it is the correct path, here is what was printed:
C:\Users\Archie\Desktop\Server.b571c7a6-3297-48eb-ac24-1bac65ef9727 (dir to copy to)
C:\Users\Archie\Desktop\Server\plugins\Solus\gameworld (src)
That is correct. And in that folder the session.lock is literally there:
http://prntscr.com/klc7xp
So I am really confused as to why it is throwing a file not found exception, I've googled it but there doesn't really seem to be a fix.
Here is the code:
private void loadWorld() {
File game = new File(Solus.get().getServer().getWorldContainer().getAbsolutePath() + uuid.toString());
if (!game.mkdir()) {
System.out.println("Couldn't generate the game: " + uuid.toString());
}
File srcDir = new File(Solus.get().getDataFolder().getAbsolutePath() + File.separator + "gameworld");
System.out.println(game.getPath() + " : " + srcDir.getAbsolutePath());
try {
FileUtils.copyDirectory(srcDir, game);
} catch (IOException e) {
e.printStackTrace();
}
WorldCreator wc = new WorldCreator(game.getAbsolutePath());
wc.createWorld();
this.world = Bukkit.getServer().createWorld(wc);
}
Code explanation:
Creates the folder to store the world data inside.
Creates the folder.
Finds the gameworld file that needs to be copied and replicated.
Copies the folder into the directory created earlier.
( Spigot ) Loads the world.

Moveing files with java

I'm trying to move files using this java code and it can locate the file but not move it, just deletes the directory I'm moving it to.
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
Scanner input = new Scanner(file);
System.out.println(file);
Path source = Paths.get(file + "");
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2");
try {
Files.move(source, target, REPLACE_EXISTING);
} catch (IOException e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
Add the file name at the end of your destination path, like below:
You could move files with File.ranameTo() method, like this:
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
In your example:
public void ch() throws Exception{
if (FC.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
java.io.File file = FC.getSelectedFile();
try {
file.renameTo(new File("C:\\Users\\Marcus\\Desktop\\2\\"+file.getName()));
} catch (Exception e){
System.out.println("Failed to move the file");
}
}else{
System.out.println("?");
}
}
If you want to use Files.move(), your target path should probably be the full path of the target file, not the destination directory where you want to place it.
Path target = Paths.get("C:\\Users\\Marcus\\Desktop\\2\\" + source.getName());
You should use Files.copy() instead of Files.move().
I strongly recommend the use of a third party tool such as Apache Commons IO's FileUtil class for this type of operation.
For example: FileUtil.moveFileToDirectory
Using these types of utilities saves you from many problems you aren't even aware are lurking. Yes, there are limitations to these common utils, but the benefits usually outweigh them in simple cases.
Google Guava is also an option, but I've got less experience there.
Your code is close but there a couple of potential issues. Before I start, I should say that I'm using a Mac (hence the path change), so while this is working for me, there may be some underlying permission issue on your system I can't account for.
1) You aren't using the name of the file you want to move to. You're using the directory you want to move the file to. That's a fair assumption, but you need to make it the fully qualified path and file name.
2) You are creating a Scanner to the to file but not using it. This probably doesn't really matter, but it's best to eliminate unnecessary code.
3) You don't validate the path that was created by getting the Path instance returned from Files.move().
Here is my example code. I tested it and it worked fine. Again, I'm using a Mac, so take that into account.
public void moveFile(){
JFileChooser fc = new JFileChooser("/");
if (fc.showOpenDialog(null) == JFileChooser.APPROVE_OPTION){
File file = fc.getSelectedFile();
System.out.println("Chosen File: " + file.getAbsolutePath());
String newFileName = System.getProperty("user.home")+File.separator+file.getName();
System.out.println("Attempting to move chosen file to destination: " + newFileName);
Path target = Paths.get(newFileName);
try {
Path newPath = Files.move(file.toPath(), target, REPLACE_EXISTING);
System.out.println("Path returned from move: " + newPath);
} catch (IOException e){
// Checked exceptions are evil.
throw new IllegalStateException("Unable to move the file: " + file.getAbsolutePath(),e);
}
}
}
The output from one of the tests:
Chosen File: /Users/dombroco/temp/simpleDbToFileTest1.txt
Attempting to move chosen file to destination: /Users/dombroco/simpleDbToFileTest1.txt
Path returned from move: /Users/dombroco/simpleDbToFileTest1.txt

reading an external file using TextIO

I don't understand how to use TextIO's readFile(String Filename)
Can someone please explain how can I read an external file?
public static void readFile(String fileName) {
if (fileName == null) // Go back to reading standard input
readStandardInput();
else {
BufferedReader newin;
try {
newin = new BufferedReader( new FileReader(fileName) );
}
catch (Exception e) {
throw new IllegalArgumentException("Can't open file \"" + fileName + "\" for input.\n"
+ "(Error :" + e + ")");
}
if (! readingStandardInput) { // close current input stream
try {
in.close();
}
catch (Exception e) {
}
}
emptyBuffer(); // Added November 2007
in = newin;
readingStandardInput = false;
inputErrorCount = 0;
inputFileName = fileName;
}
}
I had to use TextIO for a school assignment and I got stuck on it too. The problem I had was that using the Scanner class I could just pass the name of the file as long as the file was in the same folder as my class.
Scanner fileScanner = new Scanner("data.txt");
That works fine. But with TextIO, this won't work;
TextIO.readfile("data.txt"); // can't find file
You have to include the path to the file like this;
TextIo.readfile("src/package/data.txt");
Not sure if there is a way to get it to work like the Scanner class or not, but this is what I've been doing in my course at school.
The above answer (about using the correct file name) is correct, however, as a clarification, make sure that you actually use the proper file path. The file path suggested above, i.e. src/package/ will not work in all circumstances. While this will be obvious to some, for those of you who need clarification, keep reading.
For example (and I use NetBeans), if you have already moved the file into NetBeans, and the file is already in the folder you want it to be in, then right click on the folder itself, and click 'properties'. Then expand the 'file path' section by clicking on the three dots next to the hidden file path. You will see the actual file path in its entirety.
For example, if the entire file path is:
C:\Users..\NetBeansProjects\IceCream\src\icecream\icecream.dat
Then, in the java code file itself, you can write:
TextIo.readfile("src/icecream/icecream.dat");
In other words, make sure you include the words 'src' but also everything that follows the src as well. If it's in the same folder as the rest of the files, you won't need anything prior to the 'src'.

What am i doing wrong with copying my file?

So I am trying to copy one file from one place to the other using the solution found here :
Copying files from one directory to another in Java
My code creates the new directory but cant seem to find the file ,even though the landedtitlesFile is pointing to the proper path and file. I always get my "blast" comment in case you were wondering if my program gets to the end of the method.
Thank you for your time and patience.
private File landedtitlesFile = new File("C:\\Program Files (x86)\\Steam\\SteamApps\\common\\Crusader Kings II\\common\\landed_titles\\landed_titles.txt");
private String modPath = "C:\\Users\\Bernard\\Documents\\Paradox Interactive\\Crusader Kings II\\mod\\viking";
public void createCopyLandedTitles(Boolean vanilla){
if (vanilla == true) {
File dir = new File(modPath + "\\common\\landed_titles");
dir.mkdir();
try{
FileUtils.copyFile(landedtitlesFile,dir);
}
catch (IOException e ){
System.out.println("blast");
}
}
copyFile expects the second parameter to be the destination file, not a destination directory. You need to give it the target name of the file within that directory:
FileUtils.copyFile(
landedtitlesFile,
new File(dir, landedtitlesFile.getName());
Exception objects generally contain some information on the cause. If you print out the exception with e.printStackTrace(); (or rethrow it up the stack with throw new RuntimeException(e);) then you will be able to see what it says.

Java formatter - setting file directory

i am trying to create a text file in a folder (called AMCData). The file is called "File" (for the sake of this example).
I have tried using this code:
public static void OpenFile(String filename)
{
try
{
f = new Formatter("AMCData/" + filename + ".txt");
}
catch(Exception e)
{
System.out.println("error present");
}
}
But before i get the chance to even place any text in it, the catch keeps being triggered..
Could anyone inform me why this is occuring?
more information:
The folder does not exist, i was hoping it would automatically create it
If it doesn't automatically create folders, could you please link me to how to do so?
You're right, a Formatter(String) constructor needs the file to be present or createable. The most likely reason why a file cannot be created is that it references a folder that itself doesn't exist, so you should use the File.mkdirs() method, like this:
new File("AMCData").mkdirs();

Categories

Resources