java the system can not find the file specified - java

I used Java to copy file but it appeared a exception (the system can not find the file specified).
The codes are
public static void copyFile(String sourceFile, String destFile){
try {
InputStream in = new FileInputStream(sourceFile);
OutputStream os = new FileOutputStream(destFile);
byte[] buffer = new byte[1024];
int count;
while ((count = in.read(buffer)) > 0) {
os.write(buffer, 0, count);
}
in.close();
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
The test codes
public static void main(String[] args) {
String name = getFileName("D:/z/temp.txt");
String target = "D:/tem.txt";
copyFile(name, target);
}
the exception is java.io.FileNotFoundException: temp.txt(the system can not find the file specified)
The file 'temp.txt' is existence.
The path is right no problem.
I guess that is the problem of Permissions. who can come up with the answer thanks!

We need to see the method getFileName() to be sure, but based on the error message and the method name, I suspect the problem is just that this method returns only the name of the file, removing the path info, so that the file is, indeed, not found.

Related

zip file is being create but without any files in it

i copied this code directly from oracle website. i have two .png file inside d:\barcode. while i run this code myfigs.zip is created in d: drive but it is corruped and 0kb size.
code:-
public class Zip {
static final int BUFFER = 2048;
public static void main (String argv[]) {
try {
BufferedInputStream origin = null;
FileOutputStream dest = new
FileOutputStream("D:\\myfigs.zip");
CheckedOutputStream checksum = new
CheckedOutputStream(dest, new Adler32());
ZipOutputStream out = new
ZipOutputStream(new
BufferedOutputStream(checksum));
//out.setMethod(ZipOutputStream.DEFLATED);
byte data[] = new byte[BUFFER];
// get a list of files from current directory
File f = new File("D:\\barcode");
String files[] = f.list();
for (int i=0; i<files.length; i++) {
System.out.println("Adding: "+files[i]);
FileInputStream fi = new FileInputStream(files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(files[i]);
out.putNextEntry(entry);
int count;
while((count = origin.read(data, 0,
BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
System.out.println("checksum: "+checksum.getChecksum().getValue());
} catch(Exception e) {
e.printStackTrace();
}
}
}
to add more information whenever i run the code in debug mode code is successfully compiled to FileInputStream fi line then it is stopped there. the error thrown is
java.io.FileNotFoundException: barcode.png (The system cannot find the file specified)
Adding: barcode.png
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
The exception says "file not found". Your "adding" print statement gives you the answer:
Adding: barcode.png
The file "barcode.png" is not the same as the file "D:\barcode\barcode.png". You're just looking for a file named "barcode.png" in whatever your current working directory is set to, and it isn't there.
As per the docs for list() and the conclusion you should have made from your observations of your printed output and exception:
Names denoting the directory itself and the directory's parent directory are not included in the result. Each string is a file name rather than a complete path.
So you need to either:
Change your working directory to "D:\barcode" first, or
Add the parent directory name ("D:\barcode") back to the beginning of your filename ("barcode.png") before opening it, or
Look at some of the other functions File has to offer and see if there's one that helps you avoid this problem entirely.
Couple other minor notes:
It should be no surprise that the zip file was empty, given that your code threw an exception before you wrote anything to it.
"whenever i run the code in debug mode code is successfully compiled to FileInputStream fi line then it is stopped there" - This terminology is not correct. Your error was not a compiler error, it was a runtime error. The code compiled just fine.
The root cause of your problem was blind modification of the code copied from the Oracle site. Note the original comment, "get a list of files from current directory" -- This code assumed the files came from the current working directory. When you added your own directory in, that was no longer the case, and the program broke.
You can use as below code for zip one file:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Create by Cuder
*
*/
public class SampleZipFile {
/**
* Create by Cuder
*/
public static void main(String[] args) {
ZipOutputStream zipOutputStream = null;
FileInputStream fileInputStream = null;
try {
File fileInput = new File(
"D:\\eclipse4.4\\workspace\\SampleJava\\resource\\sampleZipFile.txt");
File fileOutput = new File(
"D:\\eclipse4.4\\workspace\\SampleJava\\resource\\sampleZipFile.zip");
FileOutputStream fileOutputStream = new FileOutputStream(fileOutput);
zipOutputStream = new ZipOutputStream(fileOutputStream);
fileInputStream = new FileInputStream(fileInput);
ZipEntry entry = new ZipEntry(fileInput.getName());
zipOutputStream.putNextEntry(entry);
byte[] buf = new byte[1024];
int byteRead = 0;
while ((byteRead = fileInputStream.read(buf)) > 0) {
zipOutputStream.write(buf, 0, byteRead);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (null != fileInputStream) {
fileInputStream.close();
}
if (null != zipOutputStream) {
zipOutputStream.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}

Check to run only once a day and when internet is connected

I have a java code that must save an image from a URL, once a day. I want to put the executable jar file in windows startup folder to run every time the windows starts and when connects to internet; but, the windows may be start more than one time every day. So, I want my code checks if has been ran and saved the image today, it don’t run again (the name of saved image is Wallpaper and i don't want to change its name). How can I do this? Thank you.
public static void main(String[] args) throws Exception {
String imageUrl ="http://imgs.yooz.ir/fc/m/medium-news/0170220/656760513-0.jpg";
String destinationFile = "E:\\Picture\\Wallpaper.jpg";
saveImage(imageUrl, destinationFile);
}
public static void saveImage(String imageUrl, String destinationFile) throws IOException {
URL url = new URL(imageUrl);
byte[] b = new byte[2048];
int length;
try {
InputStream is=url.openStream();
OutputStream os = new FileOutputStream(destinationFile);
while ((length = is.read(b)) != -1) {
os.write(b, 0, length);
}
is.close();
os.close();
}
}catch (UnknownHostException e){
e.printStackTrace();
}
}
You could download the image only if the current time is greater than 24 hours after the last modification time of the destination file.
final long dayMilliSec=24*60*60*1000;
final long diffMilliSec=(3*60+30)*60*1000;
File file=new File(location);
long modDay=(file.lastModified()+diffMilliSec)/dayMilliSec;
long currDay=(new Date().getTime()+diffMilliSec)/dayMilliSec;
//int a=(int) Math.ceil(b);
if (currDay==modDay){
System.exit(0);
}

Setting permissions for created directory to copy files into it

During the execution of my program it creates a directory which contains two sub-directories/two folders. Into one of these folders I need to copy a Jar-File. My programm resembles an installation routine. The copying of the Jar file is not the problem here, but the permissions of the created directories.
I tried to set the permissions of the directories (before actually creating them with the mkdirs() method) with File.setWritable(true, false) and also with the .setExecutable and .setReadable methods, but the access to the sub-directories is still denied.
Here's an excerpt of my code for the creation of one of the two sub-directories:
folderfile = new File("my/path/to/directory");
folderfile.setExecutable(true, false);
folderfile.setReadable(true, false);
folderfile.setWritable(true, false);
result = folderfile.mkdirs();
if (result) {
System.out.println("Folder created.");
}else {
JOptionPane.showMessageDialog(chooser, "Error");
}
File source = new File("src/config/TheJar.jar");
File destination = folderfile;
copyJar(source, destination);
And my "copyJar" method:
private void copyJar(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0) {
os.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
}
is.close();
os.close();
}
At os = new FileOutputStream(dest); the debugger throws a FileNotFoundException with the description that the access to the directory has been denied.
Does anyone have an idea what I am doing wrong or have a better solution for setting the permissions via Java? Thanks in advance!
A similar question was asked there are several years.
A possible solution for Java 7 and Unix system is available here : How do i programmatically change file permissions?
Or, below the best response, a example with JNA.
I hope that that will help you !
I solved the problem. In the end it was much easier to solve than expected.
The main problem was not the permission issue but the FileNotFoundException. The file that is assigned to the OutputStream is not really a file, but just a directory so that the Stream can't find it. You have to create the file before initializing the OutputStream and after that you copy your source file into the newly created file. The code:
private void copyJar(File source, File dest) throws IOException {
InputStream is = null;
File dest2 = new File(dest+"/TheJar.jar");
dest2.createNewFile();
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest2);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer))>0) {
os.write(buffer, 0, length);
}
} catch (Exception e) {
e.printStackTrace();
}
is.close();
os.close();
}

Re-Assembling a splitted file correctly

Please have a look at the following code
package normal;
import java.io.*;
import java.util.*;
public class ReGenerateFiles
{
private File inputFolder, outputFolder;
private String outputFormat, nameOfTheFile;
private FileInputStream fis;
private FileOutputStream fos;
List <Byte> al;
private byte[] buffer;
private int blockNumber = 1;
public ReGenerateFiles(File inputFile, File outputFile, String nameOfTheFile, String outputFormat)
{
this.inputFolder = inputFile;
this.outputFolder = outputFile;
this.nameOfTheFile = nameOfTheFile;
this.outputFormat = outputFormat;
}
public void reGenerate() throws IOException
{
File file[] = inputFolder.listFiles();
for(int i=0;i<file.length;i++)
{
System.out.println(file[i]);
}
for(int i=0;i<file.length;i++)
{
try
{
buffer = new byte[5000000];
int read = fis.read(buffer, 0, buffer.length);
fis.close();
writeBlock();
}
catch(IOException io)
{
io.printStackTrace();
}
finally
{
fis.close();
fos.close();
}
}
}
private void writeBlock()throws IOException
{
try
{
fos = new FileOutputStream(outputFolder+"/"+nameOfTheFile+"."+outputFormat,true);
fos.write(buffer, 0, buffer.length);
fos.flush();
fos.close();
}
catch(Exception e)
{
fos.close();
e.printStackTrace();
}
finally
{
fos.close();
}
}
}
In here, I am trying to re-assemble a splited file, back to its original file. This is how I split it (The selected answer)
Now, when I am trying to re-assemble it, I am getting an error saying something similar to "Cannot access kalimba.mp3. It is used by another program". This happens after executing 93 splitted files (there are 200 more). Why it is happening, even though I have make sure the streams are closed inside finally block?
Another question, I have assigned 500000 as the byte array value. I did this because I failed to set the byte array according to the original size of the particular file which is about to process. I assigned the byte array value as
buffer = new byte[(byte)file[i].length();
before, but it didn't work.
Please help me to solve these two issues and re-assemble the splitted file back, correctly.
That is because the buffer never fitted to the size of the actual content. It is always 50000, and the actually size vary. Thats the issue

exception during file copy in Java

I have a function that copies binary file
public static void copyFile(String Src, String Dst) throws FileNotFoundException, IOException {
File f1 = new File(Src);
File f2 = new File(Dst);
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
and the second function
private String copyDriverToSafeLocation(String driverPath) {
String safeDir = System.getProperty("user.home");
String safeLocation = safeDir + "\\my_pkcs11tmp.dll";
try {
Utils.copyFile(driverPath, safeLocation);
return safeLocation;
} catch (Exception ex) {
System.out.println("Exception occured while copying driver: " + ex);
return null;
}
}
The second function is run for every driver found in the system.
The driver file is copied and I am trying to initialize PKCS11 with that driver.
If initialization failed I go to next driver, I copy it to the tmp location and so on.
The initialization is in try/catch block
After the first failure I am no longer able to copy next driver to the standard location.
I get the exception
Exception occured while copying driver: java.io.FileNotFoundException: C:\Users\Norbert\my_pkcs11tmp.dll (The process cannot access the file because it is being used by another process)
How can I avoid the exception and safely copy the driver file?
For those curious why am I trying to copy the driver ... PKCS11 has nasty BUG, which prevents using drivers stored in the location that has "(" in the path ... and this is a case I am facing.
I will appreciate your help.
I would move the try-catch block into the copyFile method. That way you can properly handle closing the InputStreams (which is probably causing the JVM to hold onto the file handle). Something like this:
public static void copyFile(String Src, String Dst) {
try {
File f1 = new File(Src);
File f2 = new File(Dst);
FileInputStream in = new FileInputStream(f1);
FileOutputStream out = new FileOutputStream(f2);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
catch(Exception e) {
System.out.println("Exception occured while copying driver: " + ex);
}
finally {
in.close();
out.close();
}
}
Then you can remove the try-catch from the copyDriverToSafeLocation method.
Or there's the Java 7 Way:
public static void copyFile(String src, String dst) throws FileNotFoundException, IOException {
try (FileInputStream in = new FileInputStream(new File(src))) {
try (FileOutputStream out = new FileOutputStream(new File(dst))) {
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
}
}
}
Edit: And the Java 7 NIO way.
public static void copyFile(String src, String dst) throws FileNotFoundException, IOException {
copyFile(new File(src), new File(dst));
}
public static void copyFile(File src, File dst) throws FileNotFoundException, IOException {
try (FileInputStream in = new FileInputStream(src)) {
try (FileOutputStream out = new FileOutputStream(dst)) {
copyFile(in, out);
}
}
}
public static void copyFile(FileInputStream in, FileOutputStream out) throws IOException {
FileChannel cin = in.getChannel();
FileChannel cout = out.getChannel();
cin.transferTo(0, cin.size(), cout);
}
If the file is used by an other process and locked, there is no generic solutions to be able to access it. You best chance is to use FileLock but it's plateform-dependant, read the documentation, it's written that the results are "advisory", so be carefull. you can also take a look at the ReentrantReadWriteLock class.
I would choose to go with Apache Commons IO and their FileUtils.copyFile() routine(s).
Standard concise way to copy a file in Java?
I'm not sure why a problem with one file would prevent copying a different file. However, not closing a file when an exception occurs could definitely cause problems. Use try...finally to make sure you call close on every file you open.

Categories

Resources