I'm attempting to copy the file StandardQuestions.csv to a new filename with the following code:
String standardQuestions = "StandardQuestions.csv";
if(new File(standardQuestions).exists()){
try{
Path source = new File(standardQuestions).toPath();
Path dest = new File(filename).toPath();
Files.copy(source,dest);
}
catch(java.io.IOException e){JOptionPane.showMessageDialog(this,"Error: Input/Output exception.");}
}
I get an error thrown on the line Path source = new File(standardQuestions).toPath(); My error message is NoSuchMethodError, method toPath not found in class File. How could the File class not have this method? The program runs correctly on 3-4 machines, but for one user, it always throws this error. Any idea what's causing this? Is there any additional information needed to answer this question?
Since Path and toPath() are relatively recent additions to the Java library (they've been added in Java 7), I'd make sure you are using the same version of Java across the machines.
The first thing that comes up is that one user is running a significantly different version of Java. It might be particularly old or non-standard (GNU Classpath).
Have your user upgrade their Java installation version.
Related
Asked this question, having already tried possible solutions in other questions here on stack but that didn't allow me to fix the problem.
As in the title, I have created a java utility with which I have to perform operations on text files, in particular I have to perform simple operations to move between directories, copy from one directory to another, etc.
To do this I have used the java libraries java.io.File and java.nio.*, And I have implemented two functions for now,copyFile(sourcePath, targetPath) and moveFile(sourcePath, targetPath).
To develop this I am using a mac, and the files are under the source path /Users/myname/Documents/myfolder/F24/archive/, and my target path is /Users/myname/Documents/myfolder/F24/target/.
But when I run my code I get a java.nio.file.NoSuchFileException: /Users/myname/Documents/myfolder/F24/archive
Having tried the other solutions here on stack and java documentation already I haven't been able to fix this yet ... I accept any advice or suggestion
Thank you all
my code:
// copyFile: funzione chiamata per copiare file
public static boolean copyFile(String sourcePath, String targetPath){
boolean fileCopied = true;
try{
Files.copy(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
}catch(Exception e){
String sp = Paths.get(sourcePath)+"/";
fileCopied = false;
System.out.println("Non posso copiare i file dalla cartella "+sp+" nella cartella "+Paths.get(targetPath)+" ! \n");
e.printStackTrace();
}
return fileCopied;
}
Files.copy cannot copy entire directories. The first 'path' you pass to Files.copy must ALL:
Exist.
Be readable by the process that runs the JVM. This is non-trivial on a mac, which denies pretty much all disk rights to all apps by default until you give it access. This can be tricky for java apps. I'm not quite sure how you fix it (I did something on my mac to get rid of that, but I can't remember what - possibly out of the box java apps just get to read whatever they want and it's only actual mac apps that get pseudo-sandboxed. Point is, there's a chance it's mac's app access control denying it even if the unix file rights on this thing indicate you ought to be able to read it).
Be a plain old file and not a directory or whatnot.
Files.move can (usually - depends on impl and underlying OS) usually be done to directories, but not Files.copy. You're in a programming language, not a shell. If you want to copy entire directories, write code that does this.
Not sure whether my comment is understood though answered.
Ìn java SE target must not be the target directory. In other APIs of file copying
one can say COPY FILE TO DIRECTORY. In java not so; this was intentionally designed to remove one error cause.
That style would be:
Path source = Paths.get(sourcePath);
if (Files.isRegularFile(source)) {
Path target = Paths.get(targetPath);
Files.createDirectories(target);
if (Files.isDirectory(target)) {
target = Paths.get(targetPath, source.getFileName().toString());
// Or: target = target.resolve(source.getFileName().toString());
}
Files.copy(source, target, StandardCopyOption.REPLACE_EXISTING);
}
Better ensure when calling to use the full path.
I'm facing some issues with jasper and I need to try to edit SmapUtil class inside jasper.jar file
However, I'm facing some problems to do so.
I've used jd-gui to decompile the jasper.jar file, took out the SmapUtil.java file, changed the
install method from
static void install(File classFile, byte[] smap) throws IOException {
File tmpFile = new File(classFile.getPath() + "tmp");
SDEInstaller installer = new SDEInstaller(classFile, smap);
installer.install(tmpFile);
if (!classFile.delete()) {
throw new IOException("classFile.delete() failed");
}
if (!tmpFile.renameTo(classFile)) {
throw new IOException("tmpFile.renameTo(classFile) failed");
}
}
to
static void install(File classFile, byte[] smap){
File tmpFile = new File(classFile.getPath() + "tmp");
SDEInstaller installer = new SDEInstaller(classFile, smap);
installer.install(tmpFile);
while (!classFile.delete());
while (!tmpFile.renameTo(classFile));
}
it's basically to keep trying to delete the file if it doens't work the first time.
Now it's where I'm facing my problem.
If I try to compile SmapUtil.java, I face a lot of missing sources.
I've tried using javac -classpath (original)jasper.jar SmapUtil.java, but I still have a lot of sources missings.
I've downloaded a jasper-sources.jar file from god knows where and used that as a -classpath, but the missing sources remains..
How should I do that? I don't think that it should that hard to change 2 lines of a file inside a jar..
Thankss
Compiling a large project such as Tomcat can be a fairly complicated endeavour. If you try decompiling/editing/recompiling without knowing this process you will probably run into a lot of issues.
It might easier (or at least predictable) to build the entire project from sources. Once you have managed to build it, you can try editing the sources.
You should be able to checkout the sources from the project's website.
If you need to patch this class because you feel it's not working correctly, it might be worth trying submitting a bugreport
I have a simple JUnit test which checks two files have the same content. It works perfectly fine in my Unix laptop.
Here it is the test:
boolean response = false;
try {
File got = File.createTempFile("got-", ".csv");
String outputPath = got.getAbsolutePath();
testedObject.createCsvFile(outputPath);
got = new File(outputPath);
String expectedFilePath = getClass().getClassLoader().getResource("expected.csv").getFile();
File expected = new File(expectedFilePath);
response = FileUtils.contentEquals(got, expected); // Here it is the key
} catch (IOException e) {
// Nothing to do Yay!
}
Assert.assertTrue(response);
It works because if I compare both files manually, example via diff command, are exactly the same. Now.
My teem-mate codes with a Windows laptop, when he ran the test it brokes down! and we started debugging.
Visually, both files are the same; I mean in a human revision you cannot realize any difference. But If in a Cwin terminal we executed:
diff expected.csv got.csv and windows thought each line was different
And the test falls.
What is the problem, is the operative system? If that is true, Is there any way to compare file content not dependent on operative system
My guess is that this is most likely this is due to the \n value, which in unix like software is \r\n.
Anyway, the correct way to see if two files have the same content, is to hash both of them (ie via sha1) and check if the hashes matches!
This behaviour can be attributed to the Line Feed being different on both operating systems.
If you want it to be platform independent , you should pick up the value from the runtime using
System.getProperty("line.separator");
Also you might want to have a look at the char encoding for both the files
This answer can help you: Java Apache FileUtils readFileToString and writeStringToFile problems. The question's author is talking about PDF file, but this answer makes sense for your question.
My resources folder inside my jar includes a directory with several binary files. I am attempting to use this code to extract them:
try(InputStream is = ExternalHTMLThumbnail.class.getResourceAsStream("/wkhtmltoimage")) {
Files.copy(is, Paths.get("/home/dan/wkhtmltoimage");
}
This is throwing the error
java.nio.file.NoSuchFileException: /home/dan/wkhtmltoimage
Which comes from
if (errno() == UnixConstants.ENOENT)
return new NoSuchFileException(file, other, null);
in UnixException.java. Even though in Files.java the correct options are passed:
ostream = newOutputStream(target, StandardOpenOption.CREATE_NEW,
StandardOpenOption.WRITE);
from Files.copy. Of course there's not! That's why I'm trying to make it. I don't yet understand Path and Files enough to do this right. What's the best way to extract the directory and all its contents?
Confused because the docs for Files.copy claims
By default, the copy fails if the target file already exists or is a symbolic link
(Apparently it fails if the target file doesn't exist as well?)
And lists the possible exceptions, and NoSuchFileException is not one of them.
If you're using Guava:
URL url = Resources.getResource(ExternalHTMLThumbnail.class, "wkhtmltoimage");
byte[] bytes = Resources.toByteArray(url);
Files.write(bytes, new File("/my/path/myFile"));
You could of course just chain that all into one line; I declared the variables to make it more readable.
The file that does not exist may actually be the directory you're trying to create the file in.
/home/dan/wkhtmltoimage
Does /home/dan exist? Probably not if you're on a Mac.
Reading a file from the executable JAR file itself using ClassLoader.getResourceAsStream(...) is a known concept to me, but how would I do the same using Java NIO?
The target is to have a function as follows:
static String readFullyFromJar(String filename) {
final Path path = Paths.get(Main.class.getResource(fileName).toURI());
final byte[] bytes = Files.readAllBytes(path);
return new String(bytes, CHARSET_ASCII);
}
While this works fine in the IDE, I get a
java.nio.file.FileSystemNotFoundException
at com.sun.nio.zipfs.ZipFileSystemProvider.getFileSystem(ZipFileSystemProvider.java:171))
when I try this with the real JAR, even though the target file is in the correct place.
It turns out that my code above is actually correct, the issue is within Java itself.
According to this Bug ID, Java is not properly using the ZipFileSystemProvider as it should. Supposed to be fixed in Java 8. (My actual problem is described in this duplicate report)