Spark Java file upload example

In this post we will see how to upload a multipart file using Spark Java. We will have a HTML frontend where user will select a file from his/her system. Then pressing the “Upload” button the file will be posted as multipart data to server. In the server side, the multipart file will be fetched and saved to a defined directory. Using Spark Java, we can achieve this by writing just few lines of code.

Extract files from Zip archive in Java

There are few open source libraries available to extract files from Zip archive. Apache common compress is one of the popular library. We can use gradle to resolve the dependency of Apache common compress. For this, we have to make an entry under dependency in build.gradle like this: dependencies { compile 'org.apache.commons:commons-compress:1.10' } To run this sample make sure to update your path of the zip file.

Write text file in Java

There are couple of ways to write text data to file in Java. Here is one of the easy and simple way to do this. I used BufferedWriter with a FileWriter object. Since the BufferedWriter implements Closable interface, and hope we all are using Java 7 or above, so we can leverage the try-with-resource to automatically close it once the data has written. import java.io.BufferedWriter; import java.io.FileWriter; import java.io.IOException; public class FileWriteSample { public static void main(String [] argv) throws IOException { boolean append = true; try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data/outfile.

Read text file in Java

There are many ways to read a text file in Java. The sample I created here is one of the easy and quick way. I used BufferedReader with a FileReader object. The BufferedReader implements Closable interface, and hope we all are using Java 7 or above, so we can leverage the try-with-resource to automatically close it once our job done. import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class FileReadSample { public static void main(String [] argv) throws IOException { try (BufferedReader bufferedReader = new BufferedReader(new FileReader("test.