I have written the code which downloads the file from FTP server. Since I have my FTP server locally and I want to access like "ftp://localhost/alfresco". It was alfresco's FTP.
I have the following Code
public class FtpTransfer {
public static final void main(String[] args)
{
FTPClient ftp = new FTPClient();
FileOutputStream br = null;
try
{
ftp.connect("ftp://localhost/alfresco");
ftp.login("admin", "admin");
String file = "KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";
br = new FileOutputStream("file");
ftp.retrieveFile("/"+file, br);
System.out.println("Downloaded...");
}
catch(IOException exception) {
System.out.println("Error : "+exception);
}
}
}
The following exception occurs.
Error : java.net.UnknownHostException: ftp://localhost/alfresco
Please let me know how should I give the FTP Host Address?
FTPClient f = new FTPClient();
f.connect("localhost");
f.login(username, password);
FTPFile[] files = listFiles(directory);
Also See
Article from JavaWorld
JavaDoc
Here is an example demonstrating connection to a server, changing present working directory, listing files in a directory and downloading a file to some specified directory.
package test;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.SocketException;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
public class FtpTransfer {
public static final void main(String[] args) throws SocketException, IOException {
FTPClient ftp = new FTPClient();
ftp.connect("ftp.somedomain.com"); // or "localhost" in your case
System.out.println("login: "+ftp.login("username", "pass"));
ftp.changeWorkingDirectory("folder/subfolder/");
// list the files of the current directory
FTPFile[] files = ftp.listFiles();
System.out.println("Listed "+files.length+" files.");
for(FTPFile file : files) {
System.out.println(file.getName());
}
// lets pretend there is a JPEG image in the present folder that we want to copy to the desktop (on a windows machine)
ftp.setFileType(FTPClient.BINARY_FILE_TYPE); // don't forget to change to binary mode! or you will have a scrambled image!
FileOutputStream br = new FileOutputStream("C:\\Documents and Settings\\casonkl\\Desktop\\my_downloaded_image_new_name.jpg");
ftp.retrieveFile("name_of_image_on_server.jpg", br);
ftp.disconnect();
}
}
Try remove protocol ("ftp://") from your url.
And please, look at the example.
The FTPClient.connect() method takes the name of a server, not a URL. Try:
ftp.connect("localhost");
Also, you may need to put alfresco somewhere else. If it's part of the file path,
String file = "alfresco/KPUB//Admin//TMM//Pickup//TMM_TO_ARTESIA_06152010220246.xml";
Related
I have an image in a directory.
I want to make a copy of that image with a different name without doing harm to the original image in the same directory.
So there will be two same images in one folder with a different name.
I want a basic code like I tried -
File source = new File("resources/"+getImage(0));
File dest = new File("resources/");
source.renameTo("resources/"+getImage(0)+);
try {
FileUtils.copyDirectory(source, dest);
} catch (IOException e) {
e.printStackTrace();
}
When I upload the same image to the Amazon server multiple times in automation and then it starts giving issue to upload.
So we want to upload a mirror copy of image everytime.
In eclipse generally have resources folder. I want to make copy of a original image every-time before we upload and delete it after upload.
Kindly suggest some approach
You can just copy the file and use StandardCopyOption.COPY_ATTRIBUTES
public static final StandardCopyOption COPY_ATTRIBUTES
Copy attributes to the new file.
Files.copy(Paths.get(//path//to//file//and//filename),
Paths.get(//path//to//file//and//newfilename), StandardCopyOption.COPY_ATTRIBUTES);
Not a perfect solution, but Instead of handling pop-up box we can directly force file path into the form: [I have used date-stamp for creating new filenames but some different logic could also be used viz- Random String appender etc.]
import org.junit.jupiter.api.Test;
import java.io.*;
import java.nio.file.Files;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class Upload {
private static final String SRC_RESOURCES_FILE_PATH = System.getProperty("user.dir")+"/src/resources/";
File s1 = new File(SRC_RESOURCES_FILE_PATH+"Img1.png");
File s2 = new File(SRC_RESOURCES_FILE_PATH+"Img"+getDateStamp()+".png");
#Test
public void uploadFunction() throws IOException {
copyFileUsingJava7Files(s1,s2);
}
private String getDateStamp(){
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
return dateFormat.format(date).toString();
}
private static void copyFileUsingJava7Files(File source, File dest)
throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
}
I need to set password protection for Zip folder via java, not for zip folder files. Without password i should not be able to open the Zip folder.
This is the code i found from google.
public static void encrypt(String key, InputStream is, OutputStream os)
throws Throwable {encryptOrDecrypt(key, Cipher.ENCRYPT_MODE, is, os);
}
Done using winzipaes1.0.1.jar...
Sample Code...
import java.io.File;
import java.io.IOException;
import de.idyl.winzipaes.AesZipFileEncrypter;
import de.idyl.winzipaes.impl.AESEncrypterBC;
public class Practice1Main {
public static void main(String[]args) throws IOException{
File aNewZipFile = new File("src.zip");
File existingUnzippedFile = new File("src.txt");
AESEncrypterBC encrypter = new AESEncrypterBC();
encrypter.init("password", 0); // The 0 is keySize, it is ignored for AESEncrypterBC
AesZipFileEncrypter zipEncrypter = new AesZipFileEncrypter(aNewZipFile, encrypter);
zipEncrypter.add(existingUnzippedFile, "src.txt", "password");
zipEncrypter.close();
}
}
The only free library I know of that does this is winzipaes. It has an Apache licence.
Google Code project page => https://code.google.com/p/winzipaes/
Maven Repo Link => http://mvnrepository.com/artifact/de.idyl/winzipaes
I made a desktop app in java with netbeans platform. In my app I want to give separate copy-paste and cut-paste option of file or folder.
So how can I do that? I tried Files.copy(new File("D:\\Pndat").toPath(),new File("D:\\212").toPath(), REPLACE_EXISTING);. But I don't get the exact output.
If there any other option then suggest me.
In case of "cut-paste" you can use renameTo() like this:
File source = new File("////////Source path");
File destination = new File("//////////destination path");
if (!destination.exists()) {
source.renameTo(destination);
}
In case of "copy-paste" you need to read in Input and Output stream.
Use FileUtils from apache io and do FileUtils.copyDirectory(sourceDir, destDir);
You can also do the following file operations
writing to a file
reading from a file
make a directory including parent directories
copying files and directories
deleting files and directories
converting to and from a URL
listing files and directories by filter and extension
comparing file content
file last changed date
Download link for apache i/o jar.
I think this question relates to using the system clipboard for copying a file specified in a Java app and using the OS "Paste" function to copy the file to a folder. Here is a short instructional example that will show you how to add a single file to the OS clipboard for later doing an OS "Paste" function. Tweak as necessary and add error/exception checking as needed.
As a secondary, this code also places the file name on the clipboard so you can paste the file name into document editors.
package com.example.charles.clipboard;
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class JavaToSystemClipboard {
public static void main(final String[] args) throws Exception {
final File fileOut = new File("someFileThatExists");
putFileToSystemClipboard(fileOut);
}
public static void putFileToSystemClipboard(final File fileOut) throws Exception {
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
final ClipboardOwner clipboardOwner = null;
final Transferable transferable = new Transferable() {
public boolean isDataFlavorSupported(final DataFlavor flavor) {
return false;
}
public DataFlavor[] getTransferDataFlavors() {
return new DataFlavor[] { DataFlavor.javaFileListFlavor, DataFlavor.stringFlavor };
}
public Object getTransferData(final DataFlavor flavor) {
if (flavor.equals(DataFlavor.javaFileListFlavor)) {
final List<String> list = new ArrayList<>();
list.add(fileOut.getAbsolutePath());
return list;
}
if (flavor.equals(DataFlavor.stringFlavor)) {
return fileOut.getAbsolutePath();
}
return null;
}
};
clipboard.setContents(transferable, clipboardOwner);
}
}
You can write things by yourself using FileOutputStream and FileInputStream or you can used Apache Camel.
I am trying to create TFTPClient using Apache Commons Net to put file on Server (AIX OS) and TFTP service is running on that Server, there isn't any exception raised while running the below code and it seems that everything is ok, but the file didn't put on the server.
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.apache.commons.net.tftp.TFTP;
import org.apache.commons.net.tftp.TFTPClient;
public class Test {
/**
* #param args
* #throws IOException
* #throws SocketException
*/
public static void main(String[] args) throws SocketException, IOException {
int timeout=5000;
String host="192.168.1.20";
int port=22;
TFTPClient tftpClient=new TFTPClient();
tftpClient.setDefaultTimeout(60000);
tftpClient.open(69);
tftpClient.setSoTimeout(timeout);
System.out.println("DONE");
FileInputStream input = null;
File file;
file = new File("D:\\project.ear");
input = new FileInputStream(file);
try{
tftpClient.sendFile("/home/dev/project.ear", TFTP.BINARY_MODE, input, host);
}
catch (UnknownHostException e)
{
System.err.println("Error: could not resolve hostname.");
System.err.println(e.getMessage());
System.exit(1);
}
System.out.println("DONE2");
tftpClient.close();
}
}
the output of the above code was:
DONE
DONE2
which means that everything is OK but i didn't find the file in the directory specified in code.
please advice.
If you still need help, I think you should try call tftpClient.sendFile method this way:
tftpClient.sendFile("/home/dev/project.ear", TFTP.BINARY_MODE, input, InetAddress.getByName(host));
While using InetAddress.getByName(host) it should determine your host ip address either by ip string representation or hostname, as it says here. Hope it works this way.
I am trying to read a remote file in java
File f = new File("//192.168.1.120/home/hustler/file.txt");
The remote machine needs a Username and Password to allow me to access the file.
Is there a way I could pass the parameters through the java code and read the file?
package com.eiq;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs.FileObject;
import org.apache.commons.vfs.FileSystemOptions;
import org.apache.commons.vfs.Selectors;
import org.apache.commons.vfs.UserAuthenticator;
import org.apache.commons.vfs.VFS;
import org.apache.commons.vfs.auth.StaticUserAuthenticator;
import org.apache.commons.vfs.impl.DefaultFileSystemConfigBuilder;
public class RemoteFileDemo {
public static void main(String[] args) throws IOException {
String domain = "hyd\\all";
String userName = "chiranjeevir";
String password = "Acvsl#jun2013";
String remoteFilePath = "\\\\10.0.15.74\\D$\\Suman\\host.txt";
File f = new File("E:/Suman.txt"); //Takes the default path, else, you can specify the required path
if (f.exists()) {
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
//domain, username, password
UserAuthenticator auth = new StaticUserAuthenticator(domain, userName, password);
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile(remoteFilePath, opts);
System.out.println(fo.exists());
//fo.createFile();
destn.copyFrom(fo, Selectors.SELECT_SELF);
destn.close();
//InputStream is = new FileInputStream(f);
}
}
This is a program to read a file from the remote machine and store it in our local machine as file E:/Suman.txt.
Take care while writing the file path means instead of : we have to replace it with $ symbol, e.g.:
D:\Suman\Boorla\kpl.txt is wrong,
D$\\Suman\\Boorla\\kpl.txt is right.
In the above program, you have to change the domain name, username, password and file path of the remote machine.
To work with the above program we need to add the following jar files int the classpath.
commons-vfs.jar
commons-logging.jar
Another alternative with jCIFS you can easily specify authentication parameters:
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("domain", "user", "password"); // Authentication info here, domain can be null
try (InputStream is = new SmbFile("smb://192.168.1.120/home/hustler/file.txt", auth).getInputStream()) {
// Read from 'is' ...
} catch (IOException e) {
// Handle IOException
}
You can also try Commons VSF . Check UserAuthenticator
Here is the code, I've written and it is working Perfectly.
File f=new File("abc.txt"); //Takes the default path, else, you can specify the required path
if(f.exists())
{
f.delete();
}
f.createNewFile();
FileObject destn = VFS.getManager().resolveFile(f.getAbsolutePath());
UserAuthenticator auth = new StaticUserAuthenticator("", "myusername", "secret_password");
FileSystemOptions opts = new FileSystemOptions();
DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
FileObject fo = VFS.getManager().resolveFile("\\\\192.168.0.1\\direcory\\to\\GetData\\sourceFile.txt",opts);
destn.copyFrom(fo,Selectors.SELECT_SELF);
destn.close();
Now you can use the file to perform the required operations. Something like...
InputStream is = new FileInputStream(f);