Alexandre Beaudet Alexandre Beaudet - 2 months ago 9
Java Question

Automatic spaces insert during Struts2 download

What I'm trying to do :

Generate on the server a txt file and download it on the client side.
I'm using struts 2, here are the code parts :

InputStream fileInputStream;

public InputStream getFileInputStream(){
return fileInputStream;

public String execute() {
res = "toto";
fileInputStream = new StringInputStream(res);
return SUCCESS;


<action name="awesomeAction" class="pathtomyawesomeaction">
<result name="success" type="stream">
<param name="contentType">text/plain</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="id_opp.txt"</param>
<param name="bufferSize">1024</param>
<result name="error" type="redirect">/</result>

What is not working :

When I click on the link triggering the action, a file named "id_opp.txt" is actually downloaded, it contains all the text ("toto") but it adds a whitespace before each character.

" t o t o "

With server debugs, I'm sure that my variable contains "toto" server side, so it must be a config that I miss...

Any idea ?
Thanks in advance

Using import org.hsqldb.lib.StringInputStream; for the InputStream, since the String is built in that class, I can't use a FileInputStream or anything, I'm not aware of any other way to make that ?

Checking on the encoding, will update as soon as I got some results

Resolved thanks to Thomas :

Using the StringInputStream was the root of the problem, instead switched it to :
fileInputStream = new ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8));

Which build an inputStream for the "res" variable, with the actual encoding etc...


Problems like this might occur due to different encodings. Internally Java stores strings using 16-bit characters and when you convert those into a byte representation (e.g. for writing to a stream) it will use some encoding (either one the caller provides or the default encoding which often is the system encoding).

Thus it would depend on what StringInputStream is doing with the string, i.e. how it converts the string to bytes and which encoding is used (if any).

Additionally it might depend on the reader on how the txt file is interpreted if you don't add any information to indicate the encoding (like the BOM (byte order mark) for UTF-8).

Doing it as you did, i.e. using ByteArrayInputStream(res.getBytes(StandardCharsets.UTF_8)), would at least solve the problem when writing. Editors might then interpret the data correctly, even if the BOM is missing (and UTF-8 represents common characters like ISO-Latin 1 (ASCII) and thus even the "wrong" encoding in the reader might not be a problem).