How to convert FTPFIle to File using Java? - java

I need to read all the files from a shared location and returns a File Map. I use FTPClient to access the shared location. Using FTPClient I able to retrieve all the File as a FTPFile. But I want Convert FTPFile to File. please see the code.
FTPFile[] ftpFiles = ftpClient.listFiles(folderPath);
Note:- I Don't want to Create new connection every time. I want to read all in one connection

Looks like this is very old question but just wanted to update what I have done.
InputStream iStream=ftpClient.retrieveFileStream(ftpFile.getName());
File file = File.createTempFile("tmp", null);
FileUtils.copyInputStreamToFile(iStream, file);
Hopefully this is helpful.

If you only want get the name, try this code:
private File[] getRemoteFilesInFolder() {
FTPFile[] elements;
File[] files;
try {
elements = ftpClient.listFiles();
files = new File[elements.length];
for(int i=0; i< elements.length; i++) {
files[i] = new File(elements[i].getName());
}
return files;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}

Related

Read files inside a folder from a path

I need to read all files inside a folder. Here's my path c:/records/today/ and inside path there are two files data1.txt and data2.txt. After getting the files, I need to read and display it.
I already did with the first file, I just don't know how to do both.
File file = ResourceUtils.getFile("c:/records/today/data1.txt");
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
Also, you can use this to check child paths isFile or directory
Arrays.stream(ResourceUtils.getFile("c:/records/today/data1.txt").listFiles())
.filter(File::isFile)
.forEach(file -> {
try {
String content = new String(Files.readAllBytes(file.toPath()));
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
});
Please try with
File file = ResourceUtils.getFile("c:\\records\\today\\data1.txt");
See https://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
To read all the files in specific folder, you can do it somewhat like below:
File dir = new File("c:/records/today");
for (File singleFile: dir.listFiles()) {
// do file operation on singleFile
}
You can change the code slightly, and instead of using Resources.getFile use Files.walk to return a stream of files and iterate over them.
Files.walk(Paths.get("c:\\records\\today\)).forEach(x->{
try {
if (!Files.isDirectory(x))
System.out.println(Files.readAllLines(x));
//Add internal folder handling if needed with else clause
} catch (IOException e) {
//Add some exception handling as required
e.printStackTrace();
}
});

Moving from one directory to another java [duplicate]

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
With Java 7 or newer you can use Files.move(from, to, CopyOption... options).
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException, so when no exception is thrown you know that that the file was moved.
Just add the source and destination folder paths.
It will move all the files and folder from source folder to
destination folder.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Files.move(source, target, REPLACE_EXISTING);
You can use the Files object
Read more about Files
You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:
read the source file into memory
write the content to a file at the new location
delete the source file
File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
Try this :-
boolean success = file.renameTo(new File(Destdir, file.getName()));
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}

getResourceAsStream(String) with full path returns null but file exists

Well I'm realy at a loss here. I try some JOGL and want to get a texture on an Object. I usually do it like this:
Texture[] thumbs = new Texture[pics.length];
try {
for (int i = 0; i < thumbs.length; i ++){
InputStream stream = getClass().getResourceAsStream(pics[i].getPath());
data = TextureIO.newTextureData(stream, false, "jpg");
thumbs[i] = TextureIO.newTexture(data);
}
} catch (IOException e) {
e.printStackTrace();
}
Usually this works fine if the jpg-file is in the source-directory but this time the file lies elsewhere and I recieve an IOException that says the stream was null.
pics[i].getPath() returns this String: C:\beispieluser\bjoern\eigene_bilder\eckelsheim.jpg. This is the exact path where the file lies. Can somebody tell me where my thoughts took the wrong turn?
getResourceAsStream() and friends will only open "classpath resources", which are files that appear on the classpath along with your compiled classes. To open that file, use new File() or (on Java 7) Files.newInputStream().
getResourceAsStream() finds resources that are in the classpath. I'm pretty sure it won't work for an absolute path somewhere else on your disk.
You files folder is not a part of your classpath.
You can add it, but i don't think it proper way for resources like images to be a part of classpath.
Use FileInputStream:
Code:
try{
for (int i = 0; i < thumbs.length; i ++){
File file = new File(pics[i].getPath());
FileInputStream stream = new FileInputStream(file);
data = TextureIO.newTextureData(stream, false, "jpg");
thumbs[i] = TextureIO.newTexture(data);
}
} catch (IOException e) {
e.printStackTrace();
}

How do I move a file from one location to another in Java?

How do you move a file from one location to another? When I run my program any file created in that location automatically moves to the specified location. How do I know which file is moved?
myFile.renameTo(new File("/the/new/place/newName.file"));
File#renameTo does that (it can not only rename, but also move between directories, at least on the same file system).
Renames the file denoted by this abstract pathname.
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
If you need a more comprehensive solution (such as wanting to move the file between disks), look at Apache Commons FileUtils#moveFile
With Java 7 or newer you can use Files.move(from, to, CopyOption... options).
E.g.
Files.move(Paths.get("/foo.txt"), Paths.get("bar.txt"), StandardCopyOption.REPLACE_EXISTING);
See the Files documentation for more details
Java 6
public boolean moveFile(String sourcePath, String targetPath) {
File fileToMove = new File(sourcePath);
return fileToMove.renameTo(new File(targetPath));
}
Java 7 (Using NIO)
public boolean moveFile(String sourcePath, String targetPath) {
boolean fileMoved = true;
try {
Files.move(Paths.get(sourcePath), Paths.get(targetPath), StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
fileMoved = false;
e.printStackTrace();
}
return fileMoved;
}
File.renameTo from Java IO can be used to move a file in Java. Also see this SO question.
To move a file you could also use Jakarta Commons IOs FileUtils.moveFile
On error it throws an IOException, so when no exception is thrown you know that that the file was moved.
Just add the source and destination folder paths.
It will move all the files and folder from source folder to
destination folder.
File destinationFolder = new File("");
File sourceFolder = new File("");
if (!destinationFolder.exists())
{
destinationFolder.mkdirs();
}
// Check weather source exists and it is folder.
if (sourceFolder.exists() && sourceFolder.isDirectory())
{
// Get list of the files and iterate over them
File[] listOfFiles = sourceFolder.listFiles();
if (listOfFiles != null)
{
for (File child : listOfFiles )
{
// Move files to destination folder
child.renameTo(new File(destinationFolder + "\\" + child.getName()));
}
// Add if you want to delete the source folder
sourceFolder.delete();
}
}
else
{
System.out.println(sourceFolder + " Folder does not exists");
}
Files.move(source, target, REPLACE_EXISTING);
You can use the Files object
Read more about Files
You could execute an external tool for that task (like copy in windows environments) but, to keep the code portable, the general approach is to:
read the source file into memory
write the content to a file at the new location
delete the source file
File#renameTo will work as long as source and target location are on the same volume. Personally I'd avoid using it to move files to different folders.
Try this :-
boolean success = file.renameTo(new File(Destdir, file.getName()));
Wrote this method to do this very thing on my own project only with the replace file if existing logic in it.
// we use the older file i/o operations for this rather than the newer jdk7+ Files.move() operation
private boolean moveFileToDirectory(File sourceFile, String targetPath) {
File tDir = new File(targetPath);
if (tDir.exists()) {
String newFilePath = targetPath+File.separator+sourceFile.getName();
File movedFile = new File(newFilePath);
if (movedFile.exists())
movedFile.delete();
return sourceFile.renameTo(new File(newFilePath));
} else {
LOG.warn("unable to move file "+sourceFile.getName()+" to directory "+targetPath+" -> target directory does not exist");
return false;
}
}
Please try this.
private boolean filemovetoanotherfolder(String sourcefolder, String destinationfolder, String filename) {
boolean ismove = false;
InputStream inStream = null;
OutputStream outStream = null;
try {
File afile = new File(sourcefolder + filename);
File bfile = new File(destinationfolder + filename);
inStream = new FileInputStream(afile);
outStream = new FileOutputStream(bfile);
byte[] buffer = new byte[1024 * 4];
int length;
// copy the file content in bytes
while ((length = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, length);
}
// delete the original file
afile.delete();
ismove = true;
System.out.println("File is copied successful!");
} catch (IOException e) {
e.printStackTrace();
}finally{
inStream.close();
outStream.close();
}
return ismove;
}

Sending only 1mb of files from folder through web service

My question is that I want to send pdf files through web service with condition that only 1mb of files are taken from that folder containing many files.
Please help me to resolve this question.I am new to web service.
Ask me again if it not clear.
Thanks In Advance.
The following method will return a list of all the files whose total size is <= 1Mb
public List<File> getFilesList(){
File dirLoc = new File("C:\\Temp");
List<File> validFilesList = new ArrayList<File>();
File[] fileList;
final int fileSizeLimit = 1024000; // Bytes
try {
// select all the files whose size <= 1Mb
fileList = dirLoc.listFiles(new FilenameFilter() {
public boolean accept(final File dirLoc, final String fileName) {
return (new File(dirLoc + "\\" + fileName).length() <= fileSizeLimit);
}
});
long sizeCtr = fileSizeLimit;
for(File file : fileList){
if(file.length() <= sizeCtr){
validFilesList.add(file);
sizeCtr = sizeCtr - file.length();
if(sizeCtr <= 0){
break;
}
}
}
} catch (Exception e) {
e.printStackTrace();
validFilesList = new ArrayList<File>();
} finally {
fileList = null;
}
return validFilesList;
}
Well, I dont know if I have understood your requirements correctly and if this would help your problem but you can try this java solution for filtering the files from a directory.
You will get a list of files and then you can use the web-service specific code to send these files
File dirLoc = new File("C:\\California");
File[] fileList;
final int fileSize = 1024000;
try {
fileList = dirLoc.listFiles(new FilenameFilter() {
public boolean accept(final File dirLoc, final String fileName) {
return (new File(dirLoc+"\\"+fileName).length() > fileSize);
}
});
} catch (Exception e) {
e.printStackTrace();
} finally {
fileList = null;
}
This should work.
If you just require filenames, replace the File[] with String[] and .listFiles() with list()
I cannot say much about the performance though. For a small list of files it should work pretty fast.
I am not sure if this is what you want but you can pick the files and check their size by :
java.io.File file = new java.io.File("myfile.txt");
file.length();
File.length()Javadoc
Send files whose size is 1 Mb.

Categories