Java copy all JPEGs from a folder to another folder - java

How do I copy all .jpgs from a folder over to another folder using FileInputStream?
At the moment I have it as this for copying my picture over to my SMB share:
protected String doInBackground(String... params) {
File file = new File("/sdcard/Data/pics/IMG.jpg");
String filename = file.getName();
NtlmPasswordAuthentication auth1 = new NtlmPasswordAuthentication(
servername, username, password);
try {
SmbFile sfile = new SmbFile(servername + "/" + filename, auth1);
if (!sfile.exists())
sfile.createNewFile();
sfile.connect();
InputStream in = new FileInputStream(file);
SmbFileOutputStream sfos = new SmbFileOutputStream(sfile);
byte[] buf = new byte[8192];
int len;
while ((len = in.read(buf)) >= 0) {
sfos.write(buf, 0, len);
}
in.close();
sfos.close();
z = "File copied successfully";
} catch (Exception ex) {
z = z + " " + ex.getMessage().toString();
}
return z;
}
}
I had used lambdas before, like this:
File file = new File(("/sdcard/Data/pics);
File[] jpgFiles = file.listFiles((dir, name) -> name.endsWith(".jpg"));
for (File entry : jpgFiles) {
System.out.println("File: " + entry.getName());
}
but since my program also should support older versions of Android I can't use it.

Related

How to release a file in Java GUI without closing

I've created a pretty simple Java GUI to browse/load a zip file on Windows platform to begin unzipping and then do some file checking.
Everything works fine except that I have to close the GUI window in order to delete the zip file that has been opened in the GUI.In my finally block of the unzipping method, I've tried adding the following:
public static String unZip(String path)
{
int count = -1;
String savepath = "";
File file = null;
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
savepath = path.substring(0, path.lastIndexOf("\\")) + File.separator; //File saving directory
new File(savepath).mkdir(); //create the saving directory
ZipFile zipFile = null;
String topLevelDirName="";
try
{
zipFile = new ZipFile(path,Charset.forName("gbk")); //Encoding
Enumeration<?> entries = zipFile.entries();
int levelCount=0;
while(entries.hasMoreElements())
{
byte buf[] = new byte[buffer];
ZipEntry entry = (ZipEntry)entries.nextElement();
String filename = entry.getName();
boolean ismkdir = false;
if(filename.lastIndexOf("/") != -1){ //To check if there is a directory
ismkdir = true;
}
filename = savepath + filename;
if(entry.isDirectory()){ //If it is a directory
levelCount++;
file = new File(filename);
file.mkdirs();
if(levelCount==1)
topLevelDirName = filename;
continue;
}
file = new File(filename);
if(!file.exists()){
if(ismkdir){
new File(filename.substring(0, filename.lastIndexOf("/"))).mkdirs();
}
}
file.createNewFile(); //Create the file
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while((count = is.read(buf)) > -1)
{
bos.write(buf, 0, count);
}
bos.flush();
bos.close();
fos.close();
is.close();
}
zipFile.close();
}catch(IOException ioe){
ioe.printStackTrace();
}finally{
try{
if(bos != null){
bos.close();
}
if(fos != null) {
fos.close();
}
if(is != null){
is.close();
}
if(zipFile != null){
zipFile.close();
}
}catch(Exception e) {
e.printStackTrace();
}
return topLevelDirName;
}
}
However, I am still not able to delete the zip unless explicitly close the GUI.
Wonder if there is anything to do with the Windows file handle?Thanks in advance.
Java 8 introduced the try-with-resources Statement to make this kind of situation simpler and cleaner.
One of the issues you have is, if any one of the attempts to close the many resources you have open fails, then none of the others will be closed
public static String unZip(String path) throws IOException {
int count = -1;
File sourceFile = new File(path);
String name = sourceFile.getName();
name = name.substring(0, name.lastIndexOf(".zip"));
File sourcePath = new File(sourceFile.getParent(), name);
System.out.println("SavePath = " + sourcePath);
if (!sourcePath.exists() && !sourcePath.mkdirs()) {
throw new IOException("Could not create directory " + sourcePath);
}
String topLevelDirName = "";
try (ZipFile zipFile = new ZipFile(sourceFile)) {
Enumeration<?> entries = zipFile.entries();
int levelCount = 0;
byte buf[] = new byte[1024];
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String filename = entry.getName();
File file = new File(sourcePath, filename);
if (entry.isDirectory()) { //If it is a directory
levelCount++;
System.out.println("Make directory " + file);
if (!file.exists() && !file.mkdirs()) {
throw new IOException("Could not create directory " + filename);
}
} else {
System.out.println("Extract to " + file);
try (InputStream is = zipFile.getInputStream(entry);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file))) {
while ((count = is.read(buf)) > -1) {
bos.write(buf, 0, count);
}
}
}
}
}
return topLevelDirName;
}
I've update the code slightly to try and make it a little cleaner and simpler and to take advantage of the available APIs

Primefaces File Upload - ZipFile Error

I m getting this Error, when I upload to file with zipfile.
Error: Error creating zip file: java.io.FileNotFoundException: C:\fupload\qhT39xmU- (The system cannot find the file specified)
This is My Upload Method :
public String uploadToFts(UploadedFile filem, String fileType){
String fileFtsUrl = null;
String uploadUrl = fileDAO.findByUniqueProperty("name", "geturl").getPropValue();
String usr= fileDAO.findByUniqueProperty("name", "usr").getPropValue();
String pwd= fileDAO.findByUniqueProperty("name", "pwd").getPropValue();
String nameId= String.valueOf(passGen.create(1, 1, 8, 8, 0)) + "-";
try{
ClientConfig cc = new DefaultClientConfig();
Client client = Client.create(cc);
client.addFilter(new HTTPBasicAuthFilter(usr, pwd));
try {
FormDataMultiPart form = new FormDataMultiPart();
File file = new File("C:/fupload/"+nameId+"");
File thumbnail = new File("C:/fupload/"+nameId+"-tmb.jpg");
zipFile("C:/fupload/"+nameId+".zip", file, thumbnail);
File zipFile = new File("C:/fupload/"+nameId+".zip");
String urlParams = "nameId=" + nameId+ "&" +
"fileType="+fileType+"&" +
"fileName=" + zipFile.getName() + "&" +
"zipped=true";
form.bodyPart(new FileDataBodyPart("file", zipFile, MediaType.MULTIPART_FORM_DATA_TYPE));
WebResource resource = client.resource(uploadUrl + urlParams);
ClientResponse response = resource.type(MediaType.APPLICATION_OCTET_STREAM).put(ClientResponse.class, zipFile);
String respStr = response.getEntity(String.class);
if(respStr.contains("\"status\":0")){
System.out.println(respStr);
JSONObject obj = new JSONObject(respStr);
int jsonStatus = obj.getInt("status");
int jsonTxnId = obj.getInt("txnid");
String url = obj.getString("url");
fileFtsUrl = url;
} else {
addMessageToView(FacesMessage.SEVERITY_ERROR, "", "Can't uploading FTS"+respStr);
}
} catch (Exception e) {
e.printStackTrace();
}
return fileFtsUrl;
} catch (Exception e){
e.printStackTrace();
return fileFtsUrl;
}
}
ZipFile Method
public static void zipFile(String zipFile, File... srcFiles) {
try {
// create byte buffer
byte[] buffer = new byte[1024];
FileOutputStream fos = new FileOutputStream(zipFile);
ZipOutputStream zos = new ZipOutputStream(fos);
for (int i = 0; i < srcFiles.length; i++) {
File srcFile = srcFiles[i];
FileInputStream fis = new FileInputStream(srcFile);
// begin writing a new ZIP entry, positions the stream to the start of the entry data
zos.putNextEntry(new ZipEntry(srcFile.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);
}
}
I think you just need to create the file in zipFile(..), as it won't exist:
File file = new File(zipFile);
if(!file.exists()) {
file.createNewFile();
}
FileOutputStream fos = new FileOutputStream(file, false);
Or maybe better to create it before and pass it to zipFile(file, ...), so you won't have to create it again just after the call. So pass a File instead of a String as with the other arguments.
Check with
System.out.println("C:/fupload/"+nameId+"")
System.out.println("C:/fupload/"+nameId+"-tmb.jpg")
Is exist in your system?
Make sure your path is must point file in your system

Creating Folders in a Zip Folder in Java [duplicate]

This question already has answers here:
directories in a zip file when using java.util.zip.ZipOutputStream
(6 answers)
Closed 9 years ago.
My task requires me to save a file directory into a zip folder. My only problem is I need to keep the sub-folders as folders from the main Directory. The file system will look something like
C\\Friends
C:\\Friends\\Person1\\Information.txt
C:\\Friends\\Person2\\Information.txt
C:\\Friends\\Person3\\Information.txt
.
.
.
Right now I am able to write just the txt files inside of my zip folder, but in my zip folder I need to keep that folder structure. I know the way my code is right now will tell me the file I'm trying to write is closed(No access). My Functions thus far:
private String userDirectroy = "" //This is set earlier in the program
public void exportFriends(String pathToFile)
{
String source = pathToFile + ".zip";
try
{
String sourceDir = userDirectory;
String zipFile = source;
try
{
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File fileSource = new File(sourceDir);
addDirectory(zout, fileSource);
zout.close();
System.out.println("Zip file has been created!");
}
catch(Exception e)
{
}
}
catch(Exception e)
{
System.err.println("First Function: " + e);
}
}
private static void addDirectory(ZipOutputStream zout, File fileSource) {
File[] files = fileSource.listFiles();
System.out.println("Adding directory " + fileSource.getName());
for(int i=0; i < files.length; i++)
{
if(files[i].isDirectory())
{
try
{
byte[] buffer = new byte[1024];
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
}
catch(Exception e)
{
System.err.println(e);
}
addDirectory(zout, files[i]);
continue;
}
try
{
System.out.println("Adding file " + files[i].getName());
//create byte buffer
byte[] buffer = new byte[1024];
//create object of FileInputStream
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(files[i].getName()));
int length;
while((length = fin.read(buffer)) > 0)
{
zout.write(buffer, 0, length);
}
zout.closeEntry();
//close the InputStream
fin.close();
}
catch(IOException ioe)
{
System.out.println("IOException :" + ioe);
}
}
}
Any help would be much appreciated. Thank You
For each folder, you need to add a empty ZipEntry of the path.
For each file, you need to supply both the path and file name. This will require you to know the part of the path to strip off, this would be everything after the start directory
Expanded concept
So, from your example, if the start directory is C:\Friends, then the entry for C:\Friends\Person1\Information.txt should look like Person1\Information.txt
public void exportFriends(String pathToFile) {
String source = pathToFile + ".zip";
try {
String sourceDir = "C:/Friends";
String zipFile = source;
try {
FileOutputStream fout = new FileOutputStream(zipFile);
ZipOutputStream zout = new ZipOutputStream(fout);
File fileSource = new File(sourceDir);
addDirectory(zout, sourceDir, fileSource);
zout.close();
System.out.println("Zip file has been created!");
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static String getRelativePath(String sourceDir, File file) {
// Trim off the start of source dir path...
String path = file.getPath().substring(sourceDir.length());
if (path.startsWith(File.pathSeparator)) {
path = path.substring(1);
}
return path;
}
private static void addDirectory(ZipOutputStream zout, String sourceDir, File fileSource) throws IOException {
if (fileSource.isDirectory()) {
// Add the directory to the zip entry...
String path = getRelativePath(sourceDir, fileSource);
if (path.trim().length() > 0) {
ZipEntry ze = new ZipEntry(getRelativePath(sourceDir, fileSource));
zout.putNextEntry(ze);
zout.closeEntry();
}
File[] files = fileSource.listFiles();
System.out.println("Adding directory " + fileSource.getName());
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
addDirectory(zout, sourceDir, files[i]);
} else {
System.out.println("Adding file " + files[i].getName());
//create byte buffer
byte[] buffer = new byte[1024];
//create object of FileInputStream
FileInputStream fin = new FileInputStream(files[i]);
zout.putNextEntry(new ZipEntry(getRelativePath(sourceDir, files[i])));
int length;
while ((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
//close the InputStream
fin.close();
}
}
}
}

How do I download files from a server and display them in a view?

I'm trying to accomplish two things in my Android app:
Download files from Server (pdf, image, and html)
Once files downloaded, save all the files from server and display in Android Tab view
My question is, how can I download a file from a server and display it in my app?
My download code looks like this:
public void downloadFiles () {
try {
URL url = new URL ("http://google.com/nexuspads.png");
HttpURLConnection c = (HttpURLConnection) url.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
String PATH = Environment.getExternalStorageDirectory() + "/download/" ;
Log.v ("LOG_TAG" , "PATH: " + PATH);
File file = new File (PATH);
file.mkdirs();
String fileName = "image.png";
File outputFile = new File (file, fileName);
FileOutputStream fos = new FileOutputStream(outputFile);
InputStream is = c.getInputStream();
byte[] buffer = new byte [1024];
int len1 = 0 ;
while ((len1 = is.read(buffer)) != -1){
fos.write (buffer, 0, len1);
}
fos .close();
is.close();
}catch (IOException e) {
Log.d ("LOG_TAG2 ", "Error " + e );
// Toast.makeText(,"error " +e.toString(), Toast.LENGTH_LONG).show();
}
}
To list the files in a folder it can be done as follows..
String path = Environment.getExternalStorageDirectory().toString()+"/YOUR folder here/";
File f = new File(path);
final File listfile[] = f.listFiles();
String[] fileList = new String[listfile.length];
for (int i=0; i < listfile.length; i++)
{
fileList[i] = listfile[i].getName();
Log.v("Files", "FileName:" + listfile[i].getName());
}
you then could display the results in Alert Dialog or in an ListView.

Why all files in my application are written to jboss tmp directory?

I have function like this in my Bean:
public String uploadFile(UploadedFile uploadedFile) {
logger.info("Enter: uploadFile(UploadedFile uploadedFile).");
String name = uploadedFile.getName();
String extension = name.substring(name.length() - 3);
if (extension.contentEquals("peg")) {
extension = "jpeg";
}
RandomString rs = new RandomString(RANDOM_PHOTO_NAME_LENGTH);
this.randomPhotoName = rs.nextString();
String fileName = this.randomPhotoName + "." + extension;
logger.info("File name: " + name + ". Extension: " + extension + ". New fileName: " + fileName);
ServletContext sc = (ServletContext) FacesContext.getCurrentInstance()
.getExternalContext().getContext();
File f = new File(
sc.getRealPath(Constant.USER_FILE_PATH));
if (!f.exists()) {
logger.info("Folder "
+ Constant.USER_FILE_PATH
+ " nie istniej. Tworze nowy.");
f.mkdirs();
}
File backupFile = new File(
sc.getRealPath(Constant.USER_FILE_PATH
+ fileName));
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(uploadedFile.getInputStream());
out = new FileOutputStream(backupFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
} catch (IOException ioe) {
FacesContext context = FacesContext.getCurrentInstance();
FacesMessage msg = null;
msg = new FacesMessage(
"Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.");
context.addMessage(null, msg);
logger.error(
"Pojawił się nieoczekiwany błąd przy uploadowaniu pliku.",
ioe);
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
logger.info("Exit: uploadFile(UploadedFile uploadedFile).");
return fileName;
}
And all files are saved in tmp directory eg:
\jboss-5.1.0.GA\server\default\tmp\a006-czo4uq-gzzu4l42-1-gzzuk7xr-a2\TupTus.war\media\img\user-gallery\6u2fpgu3tkzniwg.JPG
Because all your files are built as:
File backupFile = new File(
sc.getRealPath(Constant.USER_FILE_PATH
+ fileName));
Sounds like sc.getRealPath() returns working directory that JBoss allocates for your application.
So, the real question is to you: where do you want to write the files? If not there, so where? If you prefer user temporary directory use new File(System.getProperty("java.io.tmpdir"), fileName) and write there.
If you want to be able to configure the path out of the box you can store this path either in DB or configuration file or pass it via your custom system properties when you are running JBoss using command line switch -D.

Categories

Resources