Files.copy(src, dst) throws NoSuchFileException - java

The program:
import java.io.IOException;
import java.nio.file.*;
import java.io.*;
public class Copier {
public static void main(String[] args)
{
try
{
File src = new File("C:\\Users\\k\\Desktop\\sandeep.txt");
File dstn = new File("C:\\Users\\k\\Desktop\\sandeep1.txt");
Files.copy(src.toPath(), dstn.toPath());
}
catch(IOException e) {
System.out.println(e.toString());
}
}
}
On my Desktop, sandeep.txt exists while sandeep1.txt doesn't. I have some text written in sandeep.txt that I want to copy to sandeep1.txt (after its creation). But when I try to do so, it is throwing the exception: java.nio.file.NoSuchFileException: C:\Users\k\Desktop\sandeep1.txt
This question has been asked by someone but is still unanswered so I am asking this again. Thank you so much in advance!
EDIT: In the beginning I tried Files.copy(src, dstn) but it didn't work so I tried Files.copy(dstn, src) and it still didn't work. While posting here I forgot to change it back. Now I have corrected it. Please have a look again.
SOLVED: I did a mistake while creating the file. I created a new text file and named it sandeep.txt. So effectively this file has name sandeep.txt.txt. I am embarrassed that I did this mistake but I will remember it for long. Can't thank you all enough for giving your valuable time.

janos is correct that you have the order wrong. However, you can provide a 3rd, a java.nio.file.CopyOptions parameter with a few options, the defaults can be found in java.nio.file.StandardCopyOption.
common case would look like this:
Files.copy(p1.toPath(), p2.toPath(), StandardCopyOption.REPLACE_EXISTING);

Related

import org.yaml cannot be resolved error

If anyone has any experience working with Yaml (.yml extension files), I could use some assistance. I am trying to write a little program that reads .yml files from a folder I made on my desktop.
import java.io.IOException;
import java.io.InputStream;
import org.yaml.snakeyaml.Yaml
public class readYaml {
public static void main(String[] args) throws IOException {
Yaml yaml = new Yaml();
try (InputStream in = readYaml.class.getResourceAsStream("/Collections.yml")) {
Question question = yaml.loadAs(in, Question.class);
System.out.println(question);
}
}
}
EDIT
I created a resources folder in my project file in response to an error on line 8 stating "This is coming from an error I am getting from an error I am getting on line 8, stating "The import org.yaml.snakeyaml.Yaml cannot be resolved"", but now I am getting this error. I think it will be best explained in screen shots. enter image description here
and this happens on my project folder
enter image description here
I hope this makes things clearer to understand.

Opening a file FileNotFoundException with scanner in Java, Eclipse, Ubuntu

I'm trying to write a parser to a file called "x". I want to use scanner. I tryied to follow actions from a tutorial: https://www.youtube.com/watch?v=3RNYUKxAgmw.
package q;
import java.io.File;
import java.util.Scanner;
public class Parser {
public static void main(String [] args) {
Scanner x = new Scanner(new File("/home/x/eclipse-workspace/q/src/q/x.txt"));
String s=x.nextLine();
System.out.print(s);
}
}
The file that I want to open is called "x", its text file. We can see it in Package Explorer on left side. I clicked right on its properties. There is visible file locatization.
There appears FileNotFoundException as on the picture. I doesn't understand why this file cannot be opened.
[update] But I'm not sure if this is what
There appears FileNotFoundException as on the picture. I doesn't
understand why this file cannot be opened.
That's not what's happening. The error is in compilation time (the program has not executed, it doesn't know if the file -will- exist). The compiler is telling you "this method/constructor, according to its declaration, can throw an Exception (in this case: a FileNotFoundException ) at run time; you have not told me what to do in that case".
You really need to read about how Exceptions are treated in Java.
For a quick remedy, add a throws Exception to your main declaration. (Bear in mind: that is an awful thing to do if you don't really understand what are you doing)

Java: Nothing will read in this file

Before I start, I'd like to say that I've spent 4 hours today, 6 hours yesterday and 3 hours before that researching this issue. I've read every post I can find, followed every instruction to the letter, restarted my project, reinstalled my IDE (Netbeans) and even fresh installed my OS, and I haven't found a single piece of helpful advice, so I figured I needed to ask for help.
AND YES, I HAVE PUT THE FILE IN THE RIGHT LOCATION
... As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents. I've checked and changed and defaulted the root directory many times. PLEASE don't tell me to just use an exception handler. The file the program reads in is guaranteed to exist and contain something.
So here's my question:
I'm trying to input and read from a file, however, the result is always that the file can't be found. Here's an example of my code (and it really is down to this atm):
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
FileReader inputFile = new FileReader(args[0]);
}
}
Here are two of the errors I get (I also get Filenotfound errors, but I don't think I need to add that):
Exception in thread "main" java.lang.RuntimeException: Uncompilable source
code - unreported exception java.io.FileNotFoundException; must be caught or
declared to be thrown
at project2.Project2.main(Project2.java:14)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 1 second)
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Scanner.java:1540)
at project2.Project2.main(Project2.java:24)
C:\Users\jarre\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53:
Java returned: 1
BUILD FAILED (total time: 0 seconds)
That's it. The file name comes from the arguments, and I have tried every possible variation of the name. I have tried naming the file outside of the arguments, as just the file name itself and also with an explicit file path.
Using a scanner won't let me read anything in. FileReader won't even run.
The text file has no special formatting or characters, and I've used the one I was supplied with and multiple that I hand typed just in case there was an issue with the one I was given. I have also made sure that ".txt" is never read or used twice (I keep my extensions on, anyway).
I have checked attributes and permissions of all files and the Netbeans program itself. I've also made sure that the text files were included in the project build.
I am not using any additional code right now, as I can't do anything until I'm sure that I can read in a file, and then output one as well. I also know that the text files aren't corrupt because I can read them in Python just fine, however, I have to use Java and I have to use Netbeans.
This is a new problem for me, I've always been able to read in files fine, and I've exhausted my options. I really need some help if anyone has any ideas.
The first exception (java.lang.RuntimeException: Uncompilable source
code) is thrown because the code that you have shown us is not valid java source code.
new FileReader(args[0]) is declared as throwing FileNotFoundException and according to the rules of the java language you either have to catch this exception or declare your main method as throwing this exception.
One way to fix this problem is to write your main method like this:
public static void main(String[] args) throws FileNotFoundException {
FileReader inputFile = new FileReader(args[0]);
}
It seems that you have solved this issue because the second exception (java.util.NoSuchElementException: No line found) is thrown by the Scanner.nextLine() method if you try to read past the end of the file.
Since you have not shown any code using the Scanner class it's hard to tell where to problem is in this case.
As a matter of fact, I've put the file in EVERY location. There's a copy in every folder inside my project and also a copy in the overall Projects folder, and also in My Documents.
Don't do that. You are creating a mess with files that will be hard to cleanup. If you want to know which file your program is reading then adding the following simple line tells you the exact path and filename:
System.out.println(new File(args[0]).getAbsolutePath());
Have you ever tried with a simple, minimal example like this:
package project2;
import java.io.FileReader;
import java.io.*;
import java.util.Scanner;
public class Project2 {
public static void main(String[] args) {
System.out.println(new File(args[0]).getAbsolutePath());
FileReader inputFile = new FileReader(args[0]);
try (Scanner s = new Scanner(inputFile)) {
while (s.hasNextLine()) {
System.out.println(s.nextLine());
}
}
}
}
It should print out the name of your file with the complete path and then the contents of the file line by line.
I don't think Java is messing around with you a not found file is a not found file, please elaborate more in this issue by screens of files and directories you are working on.
I would like you to consider take a look at the following:
FileReader
Path of projects on Netbeans
I hope this helps may the code be with you.
This reads a file with no problem. I'll assume you're running JDK 8.
/**
* Read a file example
* User: mduffy
* Date: 4/21/2017
* Time: 7:48 AM
* #link http://stackoverflow.com/questions/43529600/java-nothing-will-read-in-this-file
*/
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Project2 {
public static void main(String[] args) {
if (args.length > 0) {
BufferedReader reader = null;
try (BufferedReader bufferedReader = new BufferedReader(new FileReader(args[0]))) {
bufferedReader.lines().forEach(System.out::println);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Usage: Project2 <file>");
}
}
}
Here's the input file I used:
line1
line2
hello, michael
line 4
Here's the output I got:
java Project2 .\src\main\resources\test.txt
line1
line2
hello, michael
line 4
Process finished with exit code 0

How to open the temporary directory in Java?

Dear community members,
I have a small problem with the following code. I think it should open the explorer in the C:\Users\Me\AppData\Local\Temp\ directory. However that does not work, actually nothing happens. No errors.
I have used the following code:
import java.awt.Desktop;
import java.io.File;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
try {
Desktop.getDesktop().open(File.createTempFile("abcd", ".temp").getParentFile());
} catch (IOException e) {
e.printStackTrace();
}
}
}
If I replace it with a normal file, like new File("C:\"), then it does work. Can someone explain to me why it does not work?
PS: guys I forgot to tell you I also tried it with some characters like "abcd", it still gives nothing and shows nothing!
Just use new File(System.getProperty("java.io.tmpdir")): that's the temp directory. No need for dirty tricks with the parent of a useless temporary file...
Looking at the Javadoc for the File class:
Parameters:
prefix - The prefix string to be used in generating the file's name; must be at least three characters long
So it appears that "" isn't a valid argument for the file prefix.
According to the docs for File.createTempFile(), if the prefix (first argument) contains fewer than three characters, an IllegalArgumentException will be thrown. You should see it in your console output.

Accessing Data inside of a .jar

I am currently putting a program into a .jar, and have difficulties telling it where to get its data from. The data was inside of a file in the project, and I am sure that it is located in the jar as well. But I have no clue on how to get a path into a jar.
I found the getClass().getClassLoader().getResourceAsStream() method online to get an input stream into the jar, but since I used FileReaders all the time, I dont know what to do with it as well..
I`d be very thankful for any help.
Edit:
Here is a picture of how the directory is organized:
My command window shows what happens if I run the .jar. Nullpointer in line 30. I tried it with and without .getClassLoader(), it just wont find it.
Here is the inside of the jar:
again, app is where the class files are in. Hence, via class.getResource.. I should be able to search in DataPackeg. Man, this is wearing me out.
A key concept to understand is that files don't exist inside of jars. You must instead get your data as a read-only resource, and you will need to use a path that is relative to path of your class files.
If you're still stuck, you may need to tell us more specifics about your current program, its structure, what type of data you're trying to get, where it's located in the jar file, and how you're trying to use it.
For instance, say your package structure looked like this:
So the class file is located in the codePackage package (this is Eclipse so the class files live in a universe parallel to the java files), and the resource's location is in the codePackage.images package, but relative to the class file it is the images directory, you could use the resource like so:
package codePackage;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;
public class ClassUsesResources {
private JLabel label = new JLabel();
public ClassUsesResources() {
try {
BufferedImage img = ImageIO.read(getClass().getResourceAsStream(
"images/img001s.jpg"));
ImageIcon icon = new ImageIcon(img);
label.setIcon(icon);
JOptionPane.showMessageDialog(null, label);
} catch (IOException e) {
e.printStackTrace();
System.exit(-1);
}
}
public static void main(String[] args) {
new ClassUsesResources();
}
}

Categories

Resources