I'm working on a java project that transfers files between server and client and I've managed to send a file to a desired output location, but the only problem is I have to include the full file name in the output path to save it successfully. My program runs in this way:
First it gets the path of the file to be transferred as input to the console, and then it gets the output path, again as an input to the console.
here are the codes of corresponding file name import and exports(I think the problem is somewhere here and posting this part will be sufficed)
Server Side
....
String in_filePath = null;
System.out.print("enter the file name: ");
in_filePath = sc.nextLine();
File myFile = new File( in_filePath );
System.out.println("The file chosen is being sent...");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
sc.close();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
Client Side
.....
int bufferSize = clientSocket.getReceiveBufferSize();
is = clientSocket.getInputStream();
DataInputStream clientdata = new DataInputStream(is);
String fileName = clientdata.readUTF();
System.out.println("file to be transferred is: " + fileName );
System.out.print("file output path: ");
String out_filePath;
out_filePath = sc.nextLine();
File file = new File( out_filePath );
fos = new FileOutputStream( file );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
System.out.println(fileName + " transferred successfully");
At first I haven't included the output path in my program; as expected the output path was the root project folder and it was working great as it was reading the filename and sending the file with the same name without problems. But when I implemented the output path query, the output paths I choose like "C:\" or "C:\blabla\" gives me the exception as I stated above. Moreover giving the output path as "C:\image.jpg" or "blablabla\image.jpg" works perfectly well(assuming the name of the file to be copied as image.jpg) can it be a problem with reading the file name? any help would be appreciated
edit: now I'm receiving a socket write error if I had given "c:\" (or any kind of paths like that) as output path, yet it still works well if the output path is given like "c:\image.jpg"
Assume you're executing your program on directory "C:\", and your file "image.jpg" is located on "C:\images\image.jpg".
If you provide your input as "image.jpg", it won't work. You'd have to provide "images\image.jpg" instead.
You can easily check if you've hit an actual file by adding the following line to your Server Side code:
System.out.println(myFile.isFile());
Related
I am trying to send Files in fragments using DatagramPackets in Java (part of an assignemt.) When I am trying to save the incoming File I get access denied error, but I believe that it is not a permissions issue.
Here is the brunt of it:
I let the user sending the file to choose it using FileChooser. And create a new Message object.
//....
File f = content.showFileChooser();
byte type = Byte.parseByte("4");
Message m;
try {
if (mode == 1){
m = new Message(f, content.getServerData().getFragmentSize(), (short) (sentMessages.size()+1), type);
serverThread.send(m);
}
//...
During Message creation the file gets split up into byte arrays, where the size of each array is predetermined by the user. The code is quite lengthy so I am not going to post the chopping process, but this is how I convert the File object into a big byte[] which then gets chopped up
Path p = Paths.get(file.getAbsolutePath());
this.rawData = Files.readAllBytes(p);
After the Message is created and chopped up into byte arrays I send them using DatagramPackets. The other side then uses those to create a new Message object. Once all fragments arrive rawData is extracted from the Message object again. The problem believe lies here:
Message m = receivedMessages.get(msgIndex-1);
byte[] fileData = m.getFile();
if (fileData != null){
System.out.println("All file fragments received.");
content.append("Received a file in" + m.getFragmentCount()+" fragments. Choose directory. " ,1);
//I BELIEVE THIS TO BE THE CRITICAL POINT
String filePath = content.chooseDirectory();
if (filePath == null)
return;
FileOutputStream fos;
try {
fos = new FileOutputStream(filePath);
fos.write(fileData);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Once all fragments arrive I let the user select a directory using FileChooser with DIRECTORY_ONLY choice mode. As I understand, FileOutputStream requires a full path for the new File. Do I have to send the file name and extension separately or can it be extracted from the received File data?
You are writing directory path to filePath, then try to open that directory with FileOutputStream. No wonder that doesn't work, you have to specify the filename too.
String filename = "myfile.txt"; //Or receive and set this some other way
File outFile = new File(filePath, filename);
fos = new FileOutputStream(outFile);
I don't see you sending/receiving the filename anywhere, though. You'll need to either make it constant or transfer it along with file contents.
I am trying this code to transfer file from my computer to another computer but i am getting
Exception java.io.FileNotFoundException: \192.168.1.4\D:\Color.txt (The network name cannot be found)
File source = new File("G:\\Color.txt");
File dest = new File("\\\\192.168.1.4\\D:\\Color.txt");
// File dest = new File("D:\\Color.txt");
try {
InputStream input = new FileInputStream(source);
OutputStream output = new FileOutputStream(dest);
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = input.read(buf)) > 0) {
output.write(buf, 0, bytesRead);
}
System.out.println("File Copied successfully");
input.close();
output.close();
}
catch(Exception e)
{
System.out.println("Exception "+e);
}
A file or a directory in the file system is represented by two abstract concepts in java. These abstract concepts are java.io.File and java.nio.file.Path.
The File class represents a file in the file system whereas the interface Path represents the path string of the file. In this tutorial we look at various operations on File or Path. We get a handle on the File using
Syntax :
File file = new File("c:\\filefolder\\file.txt");
But in your case first check whether location is available through file explorer,and use the same address.
I'm extracting a file from a zip archive using this code (omitting all the catch statements and other initialization statements):
zipInputStream = new ZipInputStream(new FileInputStream(file));
zipFile = new ZipFile(file);
for (Enumeration<?> em = zipFile.entries(); em.hasMoreElements();) {
String extractedFileName = em.nextElement().toString();
ZipEntry outerZipEntry = zipInputStream.getNextEntry();
if (outerZipEntry.getName().contains(searchString)) {
extractedFile = new File(outputDir + outerZipEntry.getName());
out = new FileOutputStream(outputDir + extractedFileName);
byte[] buf = new byte[1024];
int len;
while ((len = zipInputStream.read(buf)) > 0) {
out.write(buf, 0, len);
}
break;
}
}
This code works fine when extracting a file in say, /archive.zip/file_i_need.txt.
But when I'm trying to extract a file from /archive.zip/folder1/file_i_need.txt, I get an exception java.lang.NullPointerException when I try to use readLine() to read the file in:
String line = null ;
BufferedReader input = new BufferedReader(newFileReader(extractedFile)) ;
while( (line = input.readLine() ) != null ) {
...
}
I've tested it on both cases and it seems like this code will not work when the file is inside a folder because the extractedFileName is 'folder/file_i_need.txt' compared to just 'file_i_need.txt'.
Any suggestions you can recommend?
Thanks!
extractedFile = new File(outputDir + outerZipEntry.getName());
The problem is you're not taking into account that the entries name may contain a path element, which you are not creating, you simply try an write to the file. Why this doesn't produce an error, I'm not sure.
Are you writing these files on Windows?? This would create a file like folder1/file_i_need.txt on the file system, which is probably invalid at some level :P
Try extracting the file name from the ZipEntry
String name = outerZipEntry.getName();
name = name.substring(name.lastIndexOf("/") + 1);
Obviously, check that name actually contains a "/" first ;)
UPDATE
While I'm at it, this looks wrong
extractedFile = new File(outputDir + outerZipEntry.getName());
out = new FileOutputStream(outputDir + extractedFileName);
Basically your saying outputDir + outerZipEntry.getName() + (outputDir + outerZipEntry.getName())
UPDATE
I tested this on Windows and I get a FileNotFoundException when I try and write the file to a path that does not exist
I also tested it on my MaC and I get a FileNotFoundException
I don't know what your error handling is doing, but it's doing it wrong.
I think your issue is that you can't open a FileOutputStream on line out = new FileOutputStream(outputDir + extractedFileName);. You can't open a stream because if extractedFileName is folder1/file_i_need.txt and outputDir is, for example, C:/OutputDir then you're trying to open a stream on C:/OutputDirfolder1/file_i_need.txt. Such directory doesn't exist and out becomes null.
The post I was referring to in my comment does have a unzip operation, and ther you can see the special handling of directory entries in a zip file.
You are iterating over zip entries in two different ways:
Iteration 1:
for (Enumeration<?> em = zipFile.entries(); em.hasMoreElements();) {
Iteration 2:
ZipEntry outerZipEntry = zipInputStream.getNextEntry();
Just do one or the other. Either use the ZipFile API or the ZipInputStream API. I strongly suspect that is where the NullPointerException is coming from.
I tried creating a pdf file out of another one(in my local drive) using java.io. The thing is a file with a .pdf extension got created but im unable to open the file, it says the file is already in use and most importantly the size of the file is too large and it keeps on increasing (origin file size : 5,777kB and the newly created one file size as of now is 38,567kB). Im not that much of skilled java programmer but still i would appreciate if anyone can give me an explanation ..
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
for (int b = fis.read(); b != -1;) {
fos.write(b);
}
Simple use,
FileUtils.copyFile()
you meet the two problems
first,you have to close the resource: fis and fos,or it will say the file already in use
second,you have to use the byte[] to receive the data because pdf file is organized in byte arrays
String path = "D:\\priya_Docs\\Android pdfs\\Professional_Android_Application_Development.pdf";
File file = new File(path);
System.out.println("Located a file " + file.isFile());
String filesArray = file.getPath();
File getFile = file.getAbsoluteFile();
FileInputStream fis = new FileInputStream(getFile);
FileOutputStream fos = new FileOutputStream(
"D:\\priya_Docs\\Androiddoc.pdf");
byte[] buff=new byte[1024];
int len;
while((len=fis.read(buff))>=0) {
fos.write(buff,0,len);
}
fis.close();
fos.close();
I have a silly problem i haven't been able to figure out. Can anyone help me?
My Code is as:
String zipname = "C:/1100.zip";
String output = "C:/1100";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
ZipFile zipFile = new ZipFile(zipname);
Enumeration<?> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println("Unzipping: " + zipEntry.getName());
bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
int size;
byte[] buffer = new byte[2048];
It doesn't create a folder but debugging shows all the contents being generated.
In Order to create a folder i used the code
if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception
bos = new BufferedOutputStream(new FileOutputStream(new File(outPut)));
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
bos.flush();
bos.close();
bis.close();
}
My zip file contains images: a.jpg b.jpg... and in the same hierarchy, I have abc.xml.
I need to extract the content as is in the zip file.
Any helps here.
There are a few problems with your code: Where is outPut declared? output is not a file but a string, so exists() and mkdir() do not exist. Start by declaring output like:
File output = new File("C:/1100");
Furthermore, outPut (with big P) is not declared. It be something like output + File.seprator + zipEntry.getName().
bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName()));
Note that you don't need to pass a File to FileOutputStream, as constructors show in the documentation.
At this point, your code should work if your Zip file does not contain directory. However, when opening the output stream, if zipEntry.getName() has a directory component (for instance somedir/filename.txt), opening the stream will result in a FileNotFoundException, as the parent directory of the file you try to create does not exist. If you want to be able to handle such zip files, you will find your answer in: How to unzip files recursively in Java?