Connect files in java

Java FTP file upload tutorial and example

To write Java code that uploads a file from local computer to a remote FTP server, the Apache Commons Net API is a preferred choice of developers. It has simple and comprehensive API that makes coding with upload files to FTP server with ease.

Table of Content:

1. Apache Commons Net API for uploading files by FTP protocol

The FTPClient class provides six storeXXX() methods for transferring a local file to a remote server via FTP protocol:

    • boolean storeFile(String remote, InputStream local)
    • OutputStreamstoreFileStream(String remote)
    • boolean storeUniqueFile(InputStream local)
    • boolean storeUniqueFile(String remote, InputStream local)
    • OutputStreamstoreUniqueFileStream()
    • OutputStreamstoreUniqueFileStream(String remote)
      • Store files by providing anInputStream of the local file (those methods which have an InputStream as a parameter). This type of methods can be used when we don’t care how the bytes are transferred from the local file to the remote one, just let the system done the ins and outs.
      • Store files by writing to anOutputStream of the connection (those methods which return an OutputStream ). This type of methods is needed when we want to control how the bytes are transferred, by writing our own code for reading bytes from the local file and write these bytes to the remote file through the OutputStream object. This can be useful if we want to show progress of the upload, by calculating how many bytes are transferred over total bytes needed.

      The two ways above can be used in combination with:

        • Name the remote file explicitly (those methods which accept a String parameter called remote ).
        • Let the server names the remote file with a unique name (those methods which do not have a String parameter).
          • boolean storeFile(String remote, InputStream local)
          • OutputStreamstoreFileStream(String remote)
            • boolean setFileType(int fileType ) : determines which file type, either FTP.ASCII_FILE_TYPE or FTP.BINARY_FILE_TYPE , is used for file transfer. The default type is ASCII (plain text file), but it should be set to binary type in order to work with any files. This method must be called before a file transfer starts.
            • boolean completePendingCommand() : This method should be called after file transfer finishes, to complete the transaction entirely. It would return true if successfully completed, or false otherwise. We should check return value of this method to ensure the upload is actually successful. However, this method may not be necessary for some of storeXXX() methods.

            So it is recommended to switch to local passive mode before transferring data, by invoking the method enterLocalPassiveMode() of the FTPClient class.

            2. The proper steps to upload a file to FTP server

            To properly write code to upload files to a FTP server using Apache Commons Net API, the following steps should be followed:

              • Connect and login to the server.
              • Enter local passive mode for data connection.
              • Set file type to be transferred to binary.
              • Create an InputStream for the local file.
              • Construct path of the remote file on the server. The path can be absolute or relative to the current working directory.
              • Call one of the storeXXX() methods to begin file transfer. There are two scenarios:
                • Using an InputStream -based approach: this is the simplest way, since we let the system does the ins and outs. There is no additional code, just passing the InputStream object into the appropriate method, such as storeFile (String remote, InputStream local) method.
                • Using an OutputStream -based approach: this is more complex way, but more control. Typically we have to write some code that reads bytes from the InputStream of the local file and writes those bytes into the OutputStream which is returned by the storeXXX() method, such as storeFileStream (String remote) method.

                3. Java FTP File Upload Sample program code

                The following sample program demonstrates uploading local files to a FTP server using these two methods:

                  • boolean storeFile(String remote, InputStream local)
                  • OutputStreamstoreFileStream(String remote)
                  import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.commons.net.ftp.FTP; import org.apache.commons.net.ftp.FTPClient; /** * A program that demonstrates how to upload files from local computer * to a remote FTP server using Apache Commons Net API. * @author www.codejava.net */ public class FTPUploadFileDemo < public static void main(String[] args) < String server = "www.myserver.com"; int port = 21; String user = "user"; String pass = "pass"; FTPClient ftpClient = new FTPClient(); try < ftpClient.connect(server, port); ftpClient.login(user, pass); ftpClient.enterLocalPassiveMode(); ftpClient.setFileType(FTP.BINARY_FILE_TYPE); // APPROACH #1: uploads first file using an InputStream File firstLocalFile = new File("D:/Test/Projects.zip"); String firstRemoteFile = "Projects.zip"; InputStream inputStream = new FileInputStream(firstLocalFile); System.out.println("Start uploading first file"); boolean done = ftpClient.storeFile(firstRemoteFile, inputStream); inputStream.close(); if (done) < System.out.println("The first file is uploaded successfully."); >// APPROACH #2: uploads second file using an OutputStream File secondLocalFile = new File("E:/Test/Report.doc"); String secondRemoteFile = "test/Report.doc"; inputStream = new FileInputStream(secondLocalFile); System.out.println("Start uploading second file"); OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile); byte[] bytesIn = new byte[4096]; int read = 0; while ((read = inputStream.read(bytesIn)) != -1) < outputStream.write(bytesIn, 0, read); >inputStream.close(); outputStream.close(); boolean completed = ftpClient.completePendingCommand(); if (completed) < System.out.println("The second file is uploaded successfully."); >> catch (IOException ex) < System.out.println("Error: " + ex.getMessage()); ex.printStackTrace(); >finally < try < if (ftpClient.isConnected()) < ftpClient.logout(); ftpClient.disconnect(); >> catch (IOException ex) < ex.printStackTrace(); >> > >

                  To work with Apache Commons Net API, the commons-net-VERSION.jar file must be added to the classpath. The jar file can be picked up from within a zip distribution which can be downloaded from http://commons.apache.org/net/download_net.cgi.

                  Other Java File Upload Tutorials:

                  Other Java FTP Tutorials:

                  About the Author:

                  Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

                  Источник

                  Java NIO FileChannel

                  A Java NIO FileChannel is a channel that is connected to a file. Using a file channel you can read data from a file, and write data to a file. The Java NIO FileChannel class is NIO’s an alternative to reading files with the standard Java IO API.

                  A FileChannel cannot be set into non-blocking mode. It always runs in blocking mode.

                  Opening a FileChannel

                  Before you can use a FileChannel you must open it. You cannot open a FileChannel directly. You need to obtain a FileChannel via an InputStream, OutputStream, or a RandomAccessFile. Here is how you open a FileChannel via a RandomAccessFile:

                  RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel();

                  Reading Data from a FileChannel

                  To read data from a FileChannel you call one of the read() methods. Here is an example:

                  ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf);

                  First a Buffer is allocated. The data read from the FileChannel is read into the Buffer .

                  Second the FileChannel.read() method is called. This method reads data from the FileChannel into the Buffer . The int returned by the read() method tells how many bytes were written into the Buffer . If -1 is returned, the end-of-file is reached.

                  Writing Data to a FileChannel

                  Writing data to a FileChannel is done using the FileChannel.write() method, which takes a Buffer as parameter. Here is an example:

                  String newData = "New String to write to file. " + System.currentTimeMillis(); ByteBuffer buf = ByteBuffer.allocate(48); buf.clear(); buf.put(newData.getBytes()); buf.flip(); while(buf.hasRemaining()) < channel.write(buf); >

                  Notice how the FileChannel.write() method is called inside a while-loop. There is no guarantee of how many bytes the write() method writes to the FileChannel. Therefore we repeat the write() call until the Buffer has no further bytes to write.

                  Closing a FileChannel

                  When you are done using a FileChannel you must close it. Here is how that is done:

                  FileChannel Position

                  When reading or writing to a FileChannel you do so at a specific position. You can obtain the current position of the FileChannel object by calling the position() method.

                  You can also set the position of the FileChannel by calling the position(long pos) method.

                  long pos channel.position(); channel.position(pos +123);

                  If you set the position after the end of the file, and try to read from the channel, you will get -1 — the end-of-file marker.

                  If you set the position after the end of the file, and write to the channel, the file will be expanded to fit the position and written data. This may result in a «file hole», where the physical file on the disk has gaps in the written data.

                  FileChannel Size

                  The size() method of the FileChannel object returns the file size of the file the channel is connected to. Here is a simple example:

                  long fileSize = channel.size();

                  FileChannel Truncate

                  You can truncate a file by calling the FileChannel.truncate() method. When you truncate a file, you cut it off at a given length. Here is an example:

                  This example truncates the file at 1024 bytes in length.

                  FileChannel Force

                  The FileChannel.force() method flushes all unwritten data from the channel to the disk. An operating system may cache data in memory for performance reasons, so you are not guaranteed that data written to the channel is actually written to disk, until you call the force() method.

                  The force() method takes a boolean as parameter, telling whether the file meta data (permission etc.) should be flushed too.

                  Here is an example which flushes both data and meta data:

                  Источник

                  Читайте также:  Javascript IN Operator And String Objects
Оцените статью