Moveing files with java - 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

Related

Specifying file path in java causes FileNotFoundException

This piece of code throws a FileNotFoundException, i'm sure the file exists in my working directory, am i doing something wrong?
private void generateInvoiceNumber(){ //uses reads previous invoice number and increments it.
try {
File invoiceFile = new File("./Invoices/invoiceFile.txt");
FileWriter writer = new FileWriter(invoiceFile,false);
Scanner getter = new Scanner(invoiceFile);
this.invoiceNumber = getter.nextInt();
writer.write(++invoiceNumber);
writer.close();
getter.nextInt();
getter.close();
}
catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
My tip:
Print (in your code) the current path location.
Then you can use this path in order to find the exact path you should use in order to access your file.
Maybe you should put more concrete absolute path:
File invoiceFile = Paths.get ("C:","Invoices", "invoiceFile.txt").toFile();
or if you trying to get from current path:
File invoiceFile = Paths.get (".","Invoices", "invoiceFile.txt").toFile();
And you can check your . path:
System.out.println(new File(".").getCanonicalPath());
Which operating system you are using?
It’s better to use paths when you are constructing a path to your file like
File file = Paths.get (".","Invoices", "invoice.txt").toFile();
corrected " symbols and default root "." which is your folder where app started.

deleting a file with a java file

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);

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'.

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();

Java's createNewFile() - will it also create directories?

I've got a conditional to check if a certain file exists before proceeding (./logs/error.log). If it isn't found I want to create it. However, will
File tmp = new File("logs/error.log");
tmp.createNewFile();
also create logs/ if it doesn't exist?
No.
Use tmp.getParentFile().mkdirs() before you create the file.
File theDir = new File(DirectoryPath);
if (!theDir.exists()) theDir.mkdirs();
File directory = new File(tmp.getParentFile().getAbsolutePath());
directory.mkdirs();
If the directories already exist, nothing will happen, so you don't need any checks.
Java 8 Style
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
To write on file
Files.write(path, "Log log".getBytes());
To read
System.out.println(Files.readAllLines(path));
Full example
public class CreateFolderAndWrite {
public static void main(String[] args) {
try {
Path path = Paths.get("logs/error.log");
Files.createDirectories(path.getParent());
Files.write(path, "Log log".getBytes());
System.out.println(Files.readAllLines(path));
} catch (IOException e) {
e.printStackTrace();
}
}
}
StringUtils.touch(/path/filename.ext) will now (>=1.3) also create the directory and file if they don't exist.
No, and if logs does not exist you'll receive java.io.IOException: No such file or directory
Fun fact for android devs: calls the likes of Files.createDirectories() and Paths.get() would work when supporting min api 26.

Categories

Resources