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.
Related
I've been trying to tackle this problem for a day or two and can't seem to figure out precisely how to add text files to a zip file, I was able to figure out how to add these text files to a 7zip file which was insanely easy, but a zip file seems to me much more complicated for some reason. I want to return a zip file for user reasons btw.
Here's what I have now:
(I know the code isn't too clean at the moment, I plan to tackle that after getting the bare functionality down).
private ZipOutputStream addThreadDumpsToZipFile(File file, List<Datapoint<ThreadDump>> allThreadDumps, List<Datapoint<String>> allThreadDumpTextFiles) {
ZipOutputStream threadDumpsZipFile = null;
try {
//creat new zip file which accepts input stream
//TODO missing step: create text files containing each thread dump then add to zip
threadDumpsZipFile = new ZipFile(new FileOutputStream(file));
FileInputStream fileInputStream = null;
try {
//add data to each thread dump entry
for(int i=0; i<allThreadDumpTextFiles.size();i++) {
//create file for each thread dump
File threadDumpFile = new File("thread_dump_"+i+".txt");
FileUtils.writeStringToFile(threadDumpFile,allThreadDumpTextFiles.get(i).toString());
//add entry/file to zip file (creates block to add input to)
ZipEntry threadDumpEntry = new ZipEntry("thread_dump_"+i); //might need to add extension here?
threadDumpsZipFile.putNextEntry(threadDumpEntry);
//add the content to this entry
fileInputStream = new FileInputStream(threadDumpFile);
byte[] byteBuffer = new byte[(int) threadDumpFile.length()]; //see if this sufficiently returns length of data
int bytesRead = -1;
while ((bytesRead = fileInputStream.read(byteBuffer)) != -1) {
threadDumpsZipFile.write(byteBuffer, 0, bytesRead);
}
}
threadDumpsZipFile.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch(Exception e) {
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return threadDumpsZipFile;
}
As you can sort of guess, I have a set of Thread Dumps that I want to add to my zip file and return to the user.
Let me know if you guys need any more info!
PS: There might be some bugs in this question, I just realized with some breakpoints that the threadDumpFile.length() won't really work.
Look forward to your replies!
Thanks,
Arsa
Here's a crack at it. I think you'll want to keep the file extensions when you make your ZipEntry objects. See if you can implement the below createTextFiles() function; the rest of this works -- I stubbed that method to return a single "test.txt" file with some dummy data to verify.
void zip()
{
try {
FileOutputStream fos = new FileOutputStream("yourZipFile.zip");
ZipOutputStream zos = new ZipOutputStream(fos);
File[] textFiles = createTextFiles(); // should be an easy step
for (int i = 0; i < files.length; i++) {
addToZipFile(file[i].getName(), zos);
}
zos.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
void addToZipFile(String fileName, ZipOutputStream zos) throws Exception {
File file = new File(fileName);
FileInputStream fis = new FileInputStream(file);
ZipEntry zipEntry = new ZipEntry(fileName);
zos.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zos.write(bytes, 0, length);
}
zos.closeEntry();
fis.close();
}
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.
The following unzip finction doesn't work for all zip files.
My zip file pattern is as follows-
The Zip file contains one xml file and one folder(name- "images").
The name of the xml file is same as the zip file name.
The folder("images") may or may not contain any files.
I have validated the xml file before putting it into the zip file.
It throws exception at this line for some zip files-
FileOutputStream fout = new ileOutputStream(path.substring(0,path.length()-4)+"/"+filename);
The function is:
public boolean unZip(String path)
{
InputStream is;
ZipInputStream zis;
try
{
String filename;
is = new FileInputStream(path);
zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze;
byte[] buffer = new byte[1024];
int count;
while ((ze = zis.getNextEntry()) != null)
{
filename = ze.getName();
if (ze.isDirectory()) {
File fmd = new File(path.substring(0,path.length()-4)+"/"+filename);
fmd.mkdirs();
continue;
}
FileOutputStream fout = new FileOutputStream(path.substring(0,path.length()-4)+"/"+filename);
while ((count = zis.read(buffer)) != -1)
{
fout.write(buffer, 0, count);
}
fout.close();
zis.closeEntry();
}
zis.close();
}
catch(IOException e)
{
e.printStackTrace();
return false;
}
return true;
}
This method works fine. It was a permission issue while creating the zips in Linux platform. But function starts working properly when I changed the file permission.
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();
}
}
Here is my source code. I got the reading part but need a simple logic for my writing part which I"m not getting. Here in my current logic, data gets overwritten and I'm always able to see the last block of read data in my written file.
import java.io.File;
import java.io.FileInputStream;
java.io.FileNotFoundException;
java.io.FileOutputStream;
import java.io.IOException;
public class LoadTest
{
public void readFiles(File file) throws FileNotFoundException
{
int fsize = (int) file.length();
int part = (fsize/4)+(fsize%4);
byte[] block = new byte[part];
FileInputStream fin = new FileInputStream(file);
try
{
int val=-1;
do
{
int bytesread =0;
while(bytesread<part)
{
val = fin.read(block, bytesread, part-bytesread);
if (val<0)
break;
bytesread += val;
}
writeFiles(block,bytesread);
}
while(val>=0);
fin.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public void writeFiles(byte[] block, int len) throws IOException
{
int byteswritten = 0;
FileOutputStream fout = new FileOutputStream("input.csv");
fout.write(block, byteswritten, len+byteswritten);
byteswritten +=len;
fout.close();
}
public static void main(String[] args) throws FileNotFoundException
{
LoadTest testobj = new LoadTest();
String folder = "/Users/NiranjanSubramanian/Desktop/TestFiles";
File dir = new File(folder);
File[] files = dir.listFiles();
System.out.println("Started");
for( File entry: files)
{
testobj.readFiles(entry);
}
System.out.println("Ended");
}
}
See my comments for how to solve the issue in a simple manner. However, let me suggest to you a simple alternative to do what you're asking.
final Path dir = Paths.get("/Users/NiranjanSubramanian/Desktop/TestFiles");
try (final OutputStream out = Files.newOutputStream(Paths.get("input.csv"))) {
for (final Path file : Files.newDirectoryStream(dir)) {
Files.copy(file, out);
}
}
This relies on Java 7's new file API but is (at least in my opinion) a far cleaner solution.
There are some libs that handle it for you, or even NIO, but the simplest way to do it is the following:
int read = 0;
byte[] buff = new byte[1024];
FileInputStream fis = new FileInputStream(yourInputFile);
FileOutputStream fos = new FileOutputStream(yourOutputFile);
while((read = fis.read(buff)) >= 0){
fos.write(buff, 0, read);
}
fos.flush();
fos.close();
fis.close();
Open the file in append mode.. your code will override since the default is overwrite, not append.
To append you need to pass the append parameter as true.
change
FileOutputStream fout = new FileOutputStream("input.csv");
to
FileOutputStream fout = new FileOutputStream("input.csv", true);
How to copy streams in Java:
byte[] buffer = new byte[8192]; // or whatever you like really
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Note that you don't need the entire input in memory before you start writing, so you are saving both time and space; and handling partial reads including the probable final one is trivially easy.