I have a problem regarding on uploading a file. When I upload the files myself(localhost) it actually works but when I let other people in the same network upload their file it gives me an error:
(The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at sources.UploadAIP.actions.uploadAction.processRequest(uploadAction.java:49)
Here is my actual code:
public class uploadAction extends AbstractAppAction
{
public boolean processRequest(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response)
{
try{
Properties appProperties = getAppProperties();
String dbMap = appProperties.getProperty("dbMap");
DB db = getDBConnection(dbMap);
String myDirectory = "C:\\tmp";
String uploadedFile = request.getParameter("filename");
System.out.println("srcfile: " +myDirectory);
System.out.println("file: " +uploadedFile);
String errorMessage = "";
ServletContext sc = servlet.getServletContext();
String fileName = StringUtil.stringReplace(uploadedFile,"\\","\\");
int i = fileName.lastIndexOf("\\");
if (i > 0) {
fileName = fileName.substring(i+1);
}
File srcFile = new File(uploadedFile);
File targetDirectory = new File(myDirectory);
String dirname = StringUtil.stringReplace(targetDirectory.toString() ,"\\","\\");
System.out.println("directory name:" +dirname);
File destFile = new File(dirname+"\\"+fileName);
System.out.println(destFile);
System.out.println("here is the parent directory: " +targetDirectory);
if(!targetDirectory.exists()){
targetDirectory.mkdirs();
}
InputStream inStream;
OutputStream outStream;
try{
inStream = new FileInputStream(srcFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
fileName = StringUtil.stringReplace(uploadedFile, "\\", "\\");
int u = fileName.lastIndexOf("\\");
if (u > 0)
{
fileName = fileName.substring(i + 1);
}
if (!dirname.endsWith("\\"))
{
dirname = dirname + "\\";
}
File f = new File(dirname);
String uploadDir = dirname;
System.out.println("uploadDirectory" +uploadDir);
} catch (Exception ex) {
request.setAttribute("message", ex.toString());
ex.printStackTrace();
}
return (true);
}
}
Your code assumes that the file being uploaded is present on the same local machine, which isnt true, since you are receiving uploads from a local network.
This is why it works on your local machine, but not across a network.
To upload a file, you need a multipart form and a servlet that correctly handles a multipart request.
This tutorial should help you:
http://www.avajava.com/tutorials/lessons/how-do-i-upload-a-file-to-a-servlet.html
Related
private byte[] convertStreamToBytes(InputStream inputStream){
FileOutputStream out = null;
try {
String filename = DataUtil.hashFilename(getDocumentUri(), getFileName());
String filePath = Environment.getExternalStorageDirectory().getPath() + AESConstants.APOLLO_DOWNLOADS_NC_DIR;
//String path = context.getFilesDir() + folder;
File dir = new File(filePath);
dir.mkdirs();
filePath += filename;
File file = new File(filePath);{
AESLog.log(TAG, "filePath:: "+filePath);
if(file.exists()){
AESLog.log(TAG, "File Exist :: "+filePath);
boolean deleteStatus = file.delete();
AESLog.log(TAG, "deleteStatus:: "+deleteStatus);
}
}
if (inputStream == null)
throw new RuntimeException("stream is null");
out = new FileOutputStream(file);
byte buf[] = new byte[128];
do {
int numread = inputStream.read(buf);
if (numread <= 0)
break;
out.write(buf, 0, numread);
} while (true);
out.close();
//inputStream.close();
} catch (IOException ex) {
}finally{
try{
if(null != inputStream){
out.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
return null;
}
I am getting all file from an Api, the code above is to create a filepath and save the file in that particular path.
It was working fine until now. Issue happening when creating a filepath like "/storage/sdcard0/apollodownloads/nc/852945139"First.py".rtf" this. FileOutStream object null returning when creating this path. Whats the issue happening?
You need to escape your path, when it has special symbols , like " in your case
Escape the path something like this:
"/storage/sdcard0/apollodownloads/nc/852945139\"First.py\".rtf";
Details about escaping can be found here
im working on a spring mvc project . i want to upload image and save it to resources/img/folder.
I tried below code but it does not save the image to the directory.
#Autowired
private HttpServletRequest request;
try {
// MultipartFile file = uploadItem.getFileData();
String fileName = null;
InputStream inputStream = null;
OutputStream outputStream = null;
if (multipartFile.getSize() > 0) {
inputStream = multipartFile.getInputStream();
System.out.println("File Size:::" + multipartFile.getSize());
fileName = request.getSession().getServletContext().getRealPath("/resources/") + "/students/"
+ multipartFile.getOriginalFilename();
outputStream = new FileOutputStream(fileName);
System.out.println("OriginalFilename:" + multipartFile.getOriginalFilename());
System.out.println("fileName----"+fileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
Exception
11:00:39,436 INFO [stdout] (http--0.0.0.0-8080-5) File Size:::7346
11:00:39,436 ERROR [stderr] (http--0.0.0.0-8080-5) java.io.FileNotFoundException
: C:\jboss-as-7.1.1.Final\standalone\tmp\vfs\deployment65ea7dd580659db3\ObviousR
esponseWeb-1.2-SNAPSHOT.war-3a7509e73dad1cba\resources\students\zzzz.jpg (The sy
stem cannot find the path specified)
String saveDirectory=request.getSession().getServletContext().getRealPath("/")+"images\\";//to save to images folder
String fileName = multipartFile.getOriginalFilename();//getting file name
System.out.println("directory with file name: " + saveDirectory+fileName);
multipartFile.transferTo(new File(saveDirectory + fileName));
I am trying to create a program that will download resources from a webpage into a file. I created an mkir function that creates a directory whose name is a hexadecimal version of the hash of a given String. I then, created a saveResource function that saves a resource in a file, as well as in a byte array. However, when I try saving the resource into the file I get an error message stating: java.io.FileNotFoundException: 648451a1 (Is a directory)
Here are the functions:
public static File mkdir(String s) throws IOException
{
String dirname = s;
s = Integer.toHexString(dirname.hashCode());
File directory = new File(s);
if (!directory.exists() && !directory.mkdir())
throw new IOException("can't make directory for " + s);
return directory;
}
public static byte[] saveResource(File dir, String urlString,
String argURLString)
throws IOException, URISyntaxException
{
URL u = new URL(urlString);
URLConnection uc = u.openConnection();
urlString = uc.getContentType();
int contentLength = uc.getContentLength();
try (InputStream raw = uc.getInputStream()) {
InputStream in = new BufferedInputStream(raw);
byte[] data = new byte[contentLength];
int offset = 0;
while (offset < contentLength) {
int bytesRead = in.read(data, offset, data.length - offset);
if (bytesRead == -1) break;
offset += bytesRead;
}
if (offset != contentLength) {
throw new IOException("Only read " + offset
+ " bytes; Expected " + contentLength + " bytes");
}
urlString = u.getFile();
urlString = urlString.substring(urlString.lastIndexOf('/') + 1);
try (FileOutputStream fout = new FileOutputStream(dir)) {
fout.write(data);
fout.flush();
}
return data;
}
}
The error is simple and coming because you can't write data in directory.
Try to print dir.isDirectory() to confirm if it's directory. Since its part of argument, check the caller method.
I have this Java method to upload a file. I am trying to cater for users trying to upload a folder by compressing that folder into a zip file and upload it instead. For some reason in my case file.isDirectory() and file.isFile() are not working correctly.. even though the filename does not contain any extension, file.isFile() is returning true and isDirectory() returns false. Also directory.list() is also acting weird by returning null.
What can be the problem? Am I doing something wrong?
public File uploadFile(FileItem item, String filename, int ticket_id) throws IOException
{
FileOutputStream out = null;
InputStream fileContent = null;
File file = null;
try
{
//fullpath returns C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test
StringBuffer fullPath = new StringBuffer();
fullPath.append(Attachment.attachments_path);
fullPath.append("t");
fullPath.append(Integer.toString(ticket_id));
fullPath.append(File.separator);
fullPath.append(filename);
System.out.println("filename " + filename);
file = new File(fullPath.toString());
if (!file.exists())
{
// if directory does not exist, create it
file.getParentFile().mkdirs();
}
if (file.isFile())
{
// if file is not a folder
out = new FileOutputStream(file);
fileContent = item.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
// read all the file and write it to created file
while ((read = fileContent.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
}
else if (file.isDirectory())
{
ZipFile appZip = new ZipFile(fullPath.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");
}
}
catch (FileNotFoundException e)
{
LogFile.logError("[FileUpload.uploadFile()] " + e.getMessage());
}
catch (IOException e1)
{
LogFile.logError("[FileUpload.uploadFile()] " + e1.getMessage());
}
finally
{
if (out != null)
{
out.close();
}
if (fileContent != null)
{
fileContent.close();
}
}
return file;
}
This is the ZipFile class I am using
public class ZipFile
{
List<String> fileList = null;
String source_folder = "";
public ZipFile(String source_folder)
{
fileList = new ArrayList<String>();
this.source_folder = source_folder;
}
public void zipIt(String zipFile)
{
byte[] buffer = new byte[1024];
String source = "";
try
{
try
{
source = source_folder.substring(source_folder.lastIndexOf("\\") + 1, source_folder.length());
}
catch(Exception e)
{
source = source_folder;
}
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String file : this.fileList)
{
ZipEntry ze = new ZipEntry(source + File.separator + file);
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream(source_folder + File.separator + file);
int len;
while ((len = in.read(buffer)) > 0)
{
zos.write(buffer, 0, len);
}
in.close();
}
zos.closeEntry();
//remember close it
zos.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
public void generateFileList(File node)
{
// add file only
if(node.isFile())
{
fileList.add(generateZipEntry(node.toString()));
}
if(node.isDirectory())
{
String[] subNode = node.list();
if (subNode != null) {
for(String filename : subNode)
{
generateFileList(new File (node, filename));
}
}
}
}
private String generateZipEntry(String path)
{
return path.substring(source_folder.length() + 1, path.length());
}
}
file.list() is being done in the generateFileList method in ZipFile class. I know this is returning null since I tried detecting whether the file is a folder or a file by using filename.indexOf(".") instead of isDirectory() and isFile() since they were not working. But I wish I had an explanation for this.
Thanks for your help!
if (!file.exists()) {
// if directory does not exist, create it
file.mkdirs();
}
will create directory and test file.isDirectory() will return true
It could be a problem with the path?
C://MyDocuments//zerafbe//Documents//apache-tomcat-7.0.29//webapps//attachments//t50\test
You are mixing backslash with slash...
I tested your code block
ZipFile appZip = new ZipFile(file.toString());
appZip.generateFileList(file);
appZip.zipIt(filename + ".zip");
with a local folder and it's working perfectly. I think you are passing a invalid path. This may be the cause isFile or isDirectory methods are acting strangely. Try to add a validation statement at the starting of generateFileList method using File API:
if(!node.exists) {
// return some flag to signify error OR throw a suitable Exception
}
This should work.
public String compressData(String srcDir) {
String zipFile = srcDir+".zip";
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
File dir = new File(srcDir);
File[] files = dir.listFiles();
for (int i = 0; i < files.length; i++) {
System.out.println("Adding file: " + files[i].getName());
FileInputStream fis = new FileInputStream(files[i]);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while ((length = fis.read(buffer)) > 0) {
zos.write(buffer, 0, length);
}
zos.closeEntry();
// close the InputStream
fis.close();
}
// close the ZipOutputStream
zos.close();
}
catch (IOException ioe) {
System.out.println("Error creating zip file" + ioe);
}
return zipFile;
}
When I try to write to the file specified it comes up with the error below. I have tried closing the FileInputStream but I still come up with the same problem.
Here is the relevant code:
Error log:
Error: C:\Path\Hours Log.csv (The requested operation cannot be performed on a file with a user-mapped section open)
Code:
Creating the log:
private void writeLog() throws IOException{
//set up vars and write directories
File yearStatDir = new File("C:\\Path);
File yearStatPath = new File(yearStatDir + "\\" + "Hours Log.csv");
String yearStatString = yearStatPath.toString();
//read the files
String existingYearLog = readLogFile(yearStatString, yearStatPath);
//write the updated file
String hoursString = "1";
String dataYear = existingYearLog + hoursString;
String folderYear = "Satistics\\Yearly data\\" + yearString;
writeFile(dataYear, ".csv", folderYear, "Hours Log");
}
Writing the file:
private void writeFile(String data, String fileType, String folder, String fileName){
try{
File fileDir = new File("C:\\Path\\" + folder);
File filePath = new File(fileDir + "\\"+ fileName + fileType);
writeDir(fileDir);
// Create file
FileWriter fstream = new FileWriter(filePath);
try (BufferedWriter out = new BufferedWriter(fstream)) {
out.write(data);
}
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
Reading the file:
private static String readLogFile(String path, File f) throws IOException {
if (f.exists()){
try (FileInputStream stream = new FileInputStream(new File(path))) {
FileChannel fc = stream.getChannel();
MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
/* Instead of using default, pass in a decoder. */
fc.close();
return Charset.defaultCharset().decode(bb).toString();
}
}
else {
return "";
}
}
For anyone that comes across this, here is the alternative code that I am using now:
private static String readLogFile(String path) throws IOException {
File f = new File(path);
if(f.exists()) {
FileInputStream fis = new FileInputStream(f);
Integer fileLength = (int) (long) f.length();
byte[] b = new byte[fileLength];
int read = 0;
while (read < b.length) {
read += fis.read(b, read, b.length - read);
}
String text = new String(b);
return text;
} else {
String text = "";
return text;
}
}