I don't know why but outStream = new FileOutputStream(file) and inStream = new FileInputStream(new File(file1.getName())) throw an exception. I have no idea what to do.
Here's some code of this:
File tempf = new File(cmds[1]); //cmds is a String with filename cmds[1] and pathname cmds[2] where to move the file
File tempw = new File(cmds[2]);
if(!tempf.isAbsolute() || !tempw.isAbsolute()){//here i make paths absolute
tempf = new File(tempf.getAbsolutePath());
tempw = new File(tempw.getAbsolutePath());
}
String from = cmds[1];
String where = cmds[2];
File file1 = tempf;
File file2 = new File (tempw.toString() + "/" + new File(cmds[1]).getName());
InputStream inStream = null;
OutputStream outStream = null;
try {
inStream = new FileInputStream(new File(file1.getName())); //throws an exception
outStream = new FileOutputStream(file2); //throws an exception too
byte[] buffer = new byte[16384];
int length;
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
if (inStream != null)
inStream.close();
if (outStream != null)
outStream.close();
file1.delete();
} catch (IOException e) {
System.err.println("permission denied");
}
} else {
System.err.println("incorrect syntax");
}
continue;
}
Looks like everything should work fine but it doesn't. I am getting
java.io.FileNotFoundException: C:\Users\Maxim\IdeaProjects\Testing\OneDrive\1234.txt
But as I see it's wrong path. Real path is C:\Users\Maxim\OneDrive
UPD! It's found out that the problem is that getAbsolutePath() returns a path where the project is, but it's not the path I need. I need C:\Users\Maxim\OneDrive BUT it returns C:\Users\Maxim\IdeaProjects\Testing\OneDrive BUT! .../Testng doesn't have OneDrive!
The constructors for FileInputStream and FileOutputStream throw errors if there is a problem accessing the file, like if it doesn't exist. To stop it from throwing a FileNotFoundException, make sure you create the file before instantiating a FileInput/OutputStream object.
try{
FileInputStream fis = new FileInputStream(file);
}catch(FileNotFoundException e){
e.printStackTrace();
}
Look at the documentation here.
Related
Here i have folder(ZipFilesFolder) in that it consist of 10 zip files say one.zip,two.zip,three.zip..ten.zip,i'm passing file every time from this folder to zipFileToUnzip as zipFilename.I need the result in the same folder(ZipFilesFolder)i need to unzip those files and instead of one.zip,two.zip,..one,two,three folder has to visible.
public static void zipFileToUnzip(File zipFilename) throws IOException {
try {
//String destinationname = "D:\\XYZ";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(new FileInputStream(zipFilename));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname " + entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory == null) {
if (newFile.isDirectory()) {
break;
}
}
fileoutputstream = new FileOutputStream(
destinationname + entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
} catch (IOException e) {
}
}
This is my code ,but it is not working,could anybody help me,how to get desired output.
There are a couple of problems with your code:
it does not compile since destinationname is commented, but referenced when opening the FileOutputStream
IOExceptions are caught and ignored. If you throw them you would get error messages that could help you diagnose the problem
when opening the FileOutputStream, you just concatenate two strings without adding a path-separator in between.
if the file to be created is in a directory, the directory is not created and thus FileOutputStream cannot create the file.
streams are not closed when exceptions occur.
If you do not mind using guava, which simplifies life when it comes to copying streams to files, you could use this code instead:
public static void unzipFile(File zipFile) throws IOException {
File destDir = new File(zipFile.getParentFile(), Files.getNameWithoutExtension(zipFile.getName()));
try(ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry zipEntry = zipStream.getNextEntry();
if(zipEntry == null) throw new IOException("Empty or no zip-file");
while(zipEntry != null) {
File destination = new File(destDir, zipEntry.getName());
if(zipEntry.isDirectory()) {
destination.mkdirs();
} else {
destination.getParentFile().mkdirs();
Files.asByteSink(destination).writeFrom(zipStream);
}
zipEntry = zipStream.getNextEntry();
}
}
}
Alternatively you might also use zip4j, see also this question.
when i am trying to copy the .pdf file i am getting FileNotFoundException I am using this coding in my framework.This is my part of coding in my framework. Please could help me any one.If you need any other information just ask me..
public void copyFile(String dir, String file) {
try{
Debug.println("System.getProperty(\"reporthome\")"+System.getProperty("reporthome"));
File path = new File(System.getProperty("reporthome")+"\\jreports\\fileimport\\"+file);
FileInputStream fis = new FileInputStream(path);
Debug.println("dir+\"\\\\\"+file"+dir+"\\"+file);
FileOutputStream fos = new FileOutputStream(dir+"\\"+file);
int i = 0;
while( (i = fis.read()) != -1){
fos.write(i);
}
fis.close();
fos.close();
path.delete();
}catch(IOException io){
Debug.println(" Exception while copying file: "+io);
}
}
Try this
public void copyFile(String dir, String file) {
try{
Debug.println("System.getProperty(\"reporthome\")"+System.getProperty("reporthome"));
File path = new File(System.getProperty("reporthome")+"\\jreports\\fileimport\\"+file);
if (path.exists()){
FileInputStream fis = new FileInputStream(path);
FileOutputStream fos = new FileOutputStream(dir+"\\"+file);
int i = 0;
while( (i = fis.read()) != -1){
fos.write(i);
}
fis.close();
fos.close();
path.delete();
} else{
Debug.println("Path doesn't exist : "+ path);
}
}catch(IOException io){
Debug.println(" Exception while copying file: "+io);
}
}
Are you sure you have the file in the directory you are trying to copy it from? Are you able to Debug your code? I mean, if you are using Eclipse, its fairly easy to put breakpoints and inspect your code for this particular exception.
//Or any other solution to saving multipartfile into DB.
I tried with this way but getting error.
File fileOne = new File("file.getOrignalFileName");//what should be kept inside this method
byte[] bFile = new byte[(int) fileOne.length()];
try {
FileInputStream fileInputStream = new FileInputStream(fileOne);
//convert file into array of bytes
fileInputStream.read(bFile);
fileInputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
questionDao.saveImage(bFile);
MultipartFile file;
byte [] byteArr=file.getBytes();
InputStream inputStream = new ByteArrayInputStream(byteArr);
//Start Photo Upload with Adhaar No//
if (simpleLoanDto.getPic() != null && simpleLoanDto.getAdharNo() != null) {
String ServerDirPath = globalVeriables.getAPath() + "\\";
File ServerDir = new File(ServerDirPath);
if (!ServerDir.exists()) {
ServerDir.mkdirs();
}
// Giving File operation permission for LINUX//
IOperation.setFileFolderPermission(ServerDirPath);
MultipartFile originalPic = simpleLoanDto.getPic();
byte[] ImageInByte = originalPic.getBytes();
FileOutputStream fosFor = new FileOutputStream(
new File(ServerDirPath + "\\" + simpleLoanDto.getAdharNo() + "_"+simpleLoanDto.getApplicantName()+"_.jpg"));
fosFor.write(ImageInByte);
fosFor.close();
}
//End Photo Upload with Adhaar No//
I have to make a program to copy the serialized files from a source folder to target folder only if the target folder does not contain that
serialized file, so the first condition is to check whether the file that i am copying is already existed in target folder or not
if it exists then do not need to copy but if does not exists then copy, so this check of whether file exists or not is need to be done
at every second
source folder is C:\ter\
target folder is C:\bvg\
file to be transffered is gfr.ser
I have come up with this below program but still check is not implemented please advise how can I implement this check also..
class ScheduledTask extends TimerTask {
public void run() {
InputStream inStream = null;
OutputStream outStream = null;
try {
File source = new File("C:\\ter\\");
File target = new File("C:\\avd\\bvg\\");
// Already exists. do not copy
if (target.exists()) {
return;
}
File[] files = source.listFiles();
for (File file : files) {
inStream = new FileInputStream(file);
outStream = new FileOutputStream(target + "/" + file.getName());
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
}
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
the above approach is not working
You can use exists method of java.io.File class like this.
public void run() {
InputStream inStream = null;
OutputStream outStream = null;
try {
File source = new File("C:\\ter\\gfr.ser");
File target = new File(" C:\\bvg\\gfr.ser");
if (target.exists()){ // Already exists. do not copy
return;
}
inStream = new FileInputStream(source);
outStream = new FileOutputStream(target);
byte[] buffer = new byte[1024];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
inStream.close();
outStream.close();
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}
}
How can I access an Android resource using RandomAccessFile in Java?
Here is how I would like this to work (but it doesn't):
String fileIn = resources.getResourceName(resourceID);
Log.e("fileIn", fileIn);
//BufferedReader buffer = new BufferedReader(new InputStreamReader(fileIn));
RandomAccessFile buffer = null;
try {
buffer = new RandomAccessFile(fileIn, "r");
} catch (FileNotFoundException e) {
Log.e("err", ""+e);
}
Log output:
fileIn(6062): ls3d.gold.paper:raw/wwe_obj
The following exception appears in my console:
11-26 15:06:35.027: ERROR/err(6062): java.io.FileNotFoundException: /ls3d.gold.paper:raw/wwe_obj (No such file or directory)
Like you, my situation is much easier if I can use an instance of RandomAccessFile. The solution I finally arrived at is to simply copy the resource into a file in cache, then open that file with RandomAccessFile:
/**
* Copies raw resource to a cache file.
* #return File reference to cache file.
* #throws IOException
*/
private File createCacheFile(Context context, int resourceId, String filename)
throws IOException {
File cacheFile = new File(context.getCacheDir(), filename);
if (cacheFile.createNewFile() == false) {
cacheFile.delete();
cacheFile.createNewFile();
}
// from: InputStream to: FileOutputStream.
InputStream inputStream = context.getResources().openRawResource(resourceId);
FileOutputStream fileOutputStream = new FileOutputStream(cacheFile);
int count;
byte[] buffer = new byte[1024 * 512];
while ((count = inputStream.read(buffer)) != -1) {
fileOutputStream.write(buffer, 0, count);
}
fileOutputStream.close();
inputStream.close();
return cacheFile;
}
You would use this method thusly:
File cacheFile = createCacheFile(context, resourceId, "delete-me-please");
RandomAccessFile randomAccessFile = new RandomAccessFile(cacheFile, "r");
// Insert useful things that people want.
randomAccessFile.close();
cacheFile.delete();
Its a FileNotFound exception. That means that you do not specify well the file that you want to open at String fileIn = resources.getResourceName(resourceID);
The problem is that Android can return to you only the InputStream of the raw file or a FileDescriptor but both are not enough for the RandomAccessFile constructor.
There is an open source library called Unified I/O that you can use to achieve that you want, but I think that it will just make your project 'heavier'. Perhaps you should thought if you can avoid the RandomAccessFile somehow.
I'm using this code:
public static String readContentFromResourceFile(Context context, int resourceId)
throws IOException {
StringBuffer sb = new StringBuffer();
final String NEW_LINE = System.getProperty("line.separator");
InputStream is = context.getResources().openRawResource(resourceId);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
while ((readLine = br.readLine()) != null) {
sb.append(readLine);
sb.append(NEW_LINE);
}
} catch (IOException e) {
throw e;
} finally {
br.close();
is.close();
}
return sb.toString();
}