jFram
jFram

Reputation: 73

Read File to String in Java Servlet

I have a form in my HTML page where users fill out two text fields or upload two files, and click a single button to submit. Here is the code for the form:

<form name="submitButton" action="DAOserv" method="POST" enctype="multipart/form-data">
                <div id="SQL_form">
                    <div >
                        <textarea name="SQL" placeholder="BAU Reason"
                            rows="11"></textarea>
                        <label for="BAUInputFile">BAU File</label> <input type="file"
                            id="BAUInputFile">
                    </div>
                </div>

                <div >
                    <div >
                        <textarea name="BAU" placeholder="SQL Queries"
                            rows="11"></textarea>
                        <label for="SQLInputFile">SQL File</label> <input type="file"
                            id="SQLInputFile">
                    </div>
                </div>
                <button type="submit" >Submit</button>
            </form>

To clarify, the first DIV contains the text box and file upload button for a set of Queries, and the second contains a text box and file upload button for a business reason. The user must either upload a file or write into each of the two sections.

The button click submits both of the form fields, but what I can't figure out or find a solution to online (most post talk about uploading the file to the servlet directory) is how to simply read the files to a string, when the user has uploaded a file to one or both of the two form fields.

In essence, the servlet will check each text field, if it is null, it will check to see if there is a file that has been uploaded, and if so, it will parse the text in that file to a string.

Thanks in advance for any help!

Upvotes: 0

Views: 1250

Answers (1)

Umashankar
Umashankar

Reputation: 79

If you are on Servlet3.0

Look at this thread How to upload files to server using JSP/Servlet?

You'll get filepart content something like this

InputStream fileContent = filePart.getInputStream();

To read file content to String

  1. through Apache IOUtils

    String text = IOUtils.toString(inputStream, StandardCharsets.UTF_8.name());

  2. Java Stream reading

    StringBuilder textBuilder = new StringBuilder(); try (Reader reader = new BufferedReader(new InputStreamReader (inputStream, Charset.forName(StandardCharsets.UTF_8.name())))) { int c = 0; while ((c = reader.read()) != -1) { textBuilder.append((char) c); } }

  3. Reading with Java8

    public static String read(InputStream input) throws IOException { try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) { return buffer.lines().collect(Collectors.joining("\n")); } }

Hope this helps!

Upvotes: 1

Related Questions