I have following code which reads data from text file and prints to browser.
But when it gets data like "abc - abc " then in browser it shows junk characters like " ¬タモ"...
What could be the problem ?
fis points to text file. Read data from text file and write to browser.
thnx in advanced.
f = new File(URLDecoder.decode(filePathStr), URLDecoder.decode(fileName));
fis = new FileInputStream(f);
res.setHeader("Pragma", "no-cache");
res.setHeader("Expires", "-1");
res.setHeader("Cache-Control", "no-cache");
req.setCharacterEncoding("UTF-8");
res.setContentType("text/html;charset=UTF-8");
out = res.getWriter();
for (int i = fis.read(); i != -1; i = fis.read()) {
if (i == '\n')
out.print("</BR>");
else
out.write((byte) i);
}
try to output something manually something like
out.print("υτφ-8 chars");
Do they print correctly? If not take a look at this article How to get UTF-8 working in Java webapps? and make sure you follow the 4 steps on how to display UTF-8 Chars in your webpage.
If they print correctly then the problem lies with the FileInputStream and how you read the file.
You can try the following
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis, "UTF8");
NEW UPDATE
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
File f = new File("C:\\TEST.TXT");
FileInputStream fis = new FileInputStream(f);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
response.setHeader("Pragma", "no-cache");
response.setHeader("Expires", "-1");
response.setHeader("Cache-Control", "no-cache");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
out = response.getWriter();
for (int i = isr.read(), k = 0; i != -1; i = isr.read(), ++k) {
if (i == '\n') {
out.print("</BR>");
} else {
out.write(i);
}
out.flush();
}
} finally {
out.close();
}
}
The above code should work fine, i have tested it
Your file may not be in UTF-8. I would read all file concatenating all bytes in a array, then create an string with it and then I would print it.
Related
I am trying to display a PDF file in a web browser with spring MVC.
public void displayActiviteFiles (Activite activite, HttpServletResponse response) throws IOException {
File file = new File(activite.getLienUploadUn());
FileInputStream inputStream = new FileInputStream(file);
IOUtils.copy(inputStream, response.getOutputStream());
response.setHeader("Content-Disposition", "attachment; filename="+file.getName());
response.setContentType("application/pdf");
response.flushBuffer();
}
But I am getting weird characters instead of the pdf content.
Where am I wrong?
To answer my question and help some others in my case, this works :
File file = new File(activite.getLienUploadUn());
FileInputStream inputStream = new FileInputStream(file);
byte[] buffer = new byte[8192];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1)
{
baos.write(buffer, 0, bytesRead);
}
response.setHeader("Content-Disposition","inline; filename=\""+file.getName()+"\"");
response.setContentType("application/pdf");
ServletOutputStream outputStream = response.getOutputStream();
baos.writeTo(outputStream);
outputStream.flush();
You can display including this code.
#GetMapping(value = "/pdf")
public void showPdf(HttpServletResponse response) throws IOException {
response.setContentType("application/pdf");
InputStream inputStream = new FileInputStream(new File("/sample.pdf"));
int nRead;
while ((nRead = inputStream.read()) != -1) {
response.getWriter().write(nRead);
}
}
If it matters to anyone, then this is the 100% working solution in spring boot 1.5.11. Haven't run on manual Spring MVC projects. Maybe with some minor tweaks, can make it work.
#GetMapping(value = "/downloadFile")
public StreamingResponseBody getSteamingFile(HttpServletResponse response) throws URISyntaxException {
File file = new File(getClass().getClassLoader().getResource("templates/more/si.pdf").toURI());
//viewing in web browser
response.setContentType("application/pdf");
//for downloading the file directly if viewing is not possible
response.setHeader("Content-Disposition", "inline; filename=" + file.getName());
file = null;
//put the directory architecture according to your target directory
// generated during compilation in maven spring boot
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("templates/more/si.pdf");
return outputStream -> {
int nRead;
byte[] data = new byte[1024];
while ((nRead = inputStream.read(data, 0, data.length)) != -1) {
outputStream.write(data, 0, nRead);
}
inputStream.close();
};
}
I have a jasper report, I put it in the same package as servlets, I need to generate pdf file from it, but the code doesn't work and doesn't gives any error
public void print(String numBac , HttpServletRequest request,
HttpServletResponse response) {
try {
JasperDesign jasperDesign = JRXmlLoader
.load("fiche.jrxml");
String sql = "SELECT * FROM etudiant "
+ "INNER JOIN filiere ON etudiant.code_f=filiere.code_f "
+ "INNER JOIN lieu_nais ON etudiant.code_lieu=lieu_nais.code_lieu "
+ "INNER JOIN montant ON etudiant.code_m=montant.code_m WHERE bac='"
+ numBac + "'";
JRDesignQuery newQuery = new JRDesignQuery();
newQuery.setText(sql);
jasperDesign.setQuery(newQuery);
JasperReport report = JasperCompileManager
.compileReport(jasperDesign);
//JasperPrint print = JasperFillManager.fillReport(report, null, cnx);
//JasperViewer.viewReport(print);
byte[] byteStream;
byteStream = JasperRunManager.runReportToPdf(report, null, cnx);
OutputStream outStream = response.getOutputStream();
response.setHeader("Content-Sisposition", "inline,filename="+DOWNLOAD_FILE_NAME);
response.setContentType(FILE_TYPE);
response.setContentLength(byteStream.length);
outStream.write(byteStream, 0, byteStream.length);
} catch (Exception e) {
e.printStackTrace();
}
}
even if I want to generate jasper preview it doesn't shown up (code in comment)
What is baos for? Do you have to flush/close sos?
You can use bellow code. Here is complete Example using java servlet
Please download bellow jar file..
jasperreports-5.0.1.jar
commons-logging-1.1.2.jar
commons-digester-2.1.jar
commons-collections-3.2.1-1.0.0.jar
commons-beanutils-1.8.3.jar
groovy-all-2.1.3.jar
com.lowagie.text-2.1.7.jar
your database library
You can use like
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
String path = "D:\\Software\\iReport-5.0.0-windows-installer\\u\\report4.jrxml";
JasperReport jasReport = JasperCompileManager.compileReport(path);
System.out.println("Jasper Report : " + jasReport);
//Database connection
Connection con = /*Database Connection*/;
System.out.println(con);
//If You have any Paramert use bellow like
Map paramMap = new HashMap();
paramMap.put("id", request.getParameter("id"));
//If You don't have parameter pass null instead of paramMap
JasperPrint jasPrint = JasperFillManager.fillReport(jasReport, paramMap, con);
System.out.println("Jasper Print : " + jasPrint);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ServletOutputStream sos = response.getOutputStream();
response.setContentType("application/pdf");
JasperExportManager.exportReportToPdfStream(jasPrint, sos);
} catch (JRException ex) {
Logger.getLogger(Tests.class.getName()).log(Level.SEVERE, null, ex);
}
}
First of all, you have a spelling error here:
response.setHeader("Content-Sisposition", "inline,filename="+DOWNLOAD_FILE_NAME);
It should say "Disposition" instead of "Sisposition":
response.setHeader("Content-Disposition", "inline,filename="+DOWNLOAD_FILE_NAME);
Also, try using "attachment" instead of "inline":
response.setHeader("Content-Disposition", "attachment,filename="+DOWNLOAD_FILE_NAME);
And flush and close the outStream:
outStream.flush();
outStream.close();
Hope it helps!
In my code at the first step I write the result of the matcher to the file test1.txt. At the second step I read the content of test1.txt and use a part of speech tagger on it. My problem is that writing and reading to test1.txt works at the same time and that causes double entries in output.txt. How can I do it another way in order that reading from test1.txt begins only when writing to it ends and not at the same time?
while (matcher.find()) {
//create a new file and write to it during the search
try{
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("E:/test/test1.txt", true)));//append any given input
pWriter.println(matcher.group()); //write the result of matcher to the new file
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
}
}
System.out.println(matcher.group()); //Print the result of matcher to console
MaxentTagger tagger = new MaxentTagger("models/english-bidirectional-distsim.tagger");
FileInputStream fstream = new FileInputStream("E:/test/test1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//pick up sentences line by line from the file test1.txt and store it in the string sample
while((sample = br.readLine())!=null)
{
//tag the string
String tagged = tagger.tagString(sample);
FileWriter q = new FileWriter("E:/test/output.txt",true);
BufferedWriter out =new BufferedWriter(q);
//write it to the file output.txt
out.write(tagged);
out.newLine();
out.close();
}
}
while (matcher.find()) {
//create a new file and write to it during the search
try{
pWriter = new PrintWriter(new BufferedWriter(new FileWriter("E:/test/test1.txt", true)));//append any given input
pWriter.println(matcher.group()); //write the result of matcher to the new file
} catch (IOException ioe) {
ioe.printStackTrace();
} finally {
if (pWriter != null){
pWriter.flush();
pWriter.close();
runReader();
}
}
private void runReader(){
MaxentTagger tagger = new MaxentTagger("models/english-bidirectional-distsim.tagger");
FileInputStream fstream = new FileInputStream("E:/test/test1.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//pick up sentences line by line from the file test1.txt and store it in the string sample
while((sample = br.readLine())!=null)
{
//tag the string
String tagged = tagger.tagString(sample);
FileWriter q = new FileWriter("E:/test/output.txt",true);
BufferedWriter out =new BufferedWriter(q);
//write it to the file output.txt
out.write(tagged);
out.newLine();
out.close();
}
}
}
This is one of the options, you need to call the function with the reader after the writer is closed.
A much better way is to use a single Thread for reader and writer each
Here is an example how to synchronize two Threads: synchronize two threads in java
This is my jsp we are calling an java method
<%
PDFFileUploader.generatePDcFile(); //Calls the PDF method;
%>
This is my PDFFileUploader code
public class PDFFileUploader {
static final String UPLOAD_URL = "http://localhost:7080/pdf/GetPDFFile";
static final int BUFFER_SIZE = 4096;
public static void generatePDcFile() throws IOException
{
System.out.println("Inside generatePDC File");
// takes file path from first program's argument
String filePath = "H:/report1.pdf";
File uploadFile = new File("H:/report1.pdf");
System.out.println("File to upload: " + filePath);
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
// sets file name as a HTTP header
httpConn.setRequestProperty("fileName", uploadFile.getName());
// opens output stream of the HTTP connection for writing data
OutputStream outputStream = httpConn.getOutputStream();
// Opens input stream of the file for reading data
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Start writing data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data was written.");
outputStream.close();
inputStream.close();
//Read pdc file
//FileOutputStream test = new FileOutputStream("test");
// always check HTTP response code from server
InputStream test = null;
File pdcFile = new File("H:/report123.pdf");
FileOutputStream outputStreamTest = new FileOutputStream(pdcFile);
//byte[] bufferTest = new byte[BUFFER_SIZE];
//int bytesReadTest = -1;
//final OutputStream ostream = new FileOutputStream("/tmp/data.pdc");
int responseCode = httpConn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
/* BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()));*/
test = httpConn.getInputStream();
String message= httpConn.getResponseMessage();
System.out.println("Message is///"+message);
System.out.println("Header :: "+httpConn.getHeaderField(0));
final byte[] bufferTest = new byte[1024*14];
while (true) {
int len = test.read(bufferTest);
if (len <= 0) {
break;
}
outputStreamTest.write(bufferTest, 0, len);
}
outputStreamTest.close();
test.close();
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
System.out.println("Get File Name"+fileName);
/* Map<String, List<String>> map = httpConn.getHeaderFields();
for (Map.Entry<String, List<String>> entry : map.entrySet()) {
System.out.println("Key : " + entry.getKey() +
" ,Value : " + entry.getValue());
}*/
// String response = reader.readLine();
//System.out.println("Server's response: " + response);
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
from here a servlet is called through the URL provided above the code for doPost method for the getPDFFile Servlet is
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
// Gets file name for HTTP header
String fileName = request.getHeader("fileName");
File saveFile = new File(SAVE_DIR + fileName);
// prints out all header values
System.out.println("===== Begin headers =====");
Enumeration<String> names = request.getHeaderNames();
while (names.hasMoreElements()) {
String headerName = names.nextElement();
System.out.println(headerName + " = " + request.getHeader(headerName));
}
System.out.println("===== End headers =====\n");
// opens input stream of the request for reading data
InputStream inputStream = request.getInputStream();
// opens an output stream for writing file
/*FileOutputStream outputStream = new FileOutputStream(saveFile);*/
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
System.out.println("File written to: " + saveFile.getAbsolutePath());
int processStatus = 0;
//temp file (used for conversion)
/* boolean success = (new File
(saveFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+success);
//delete pdc file too
boolean successtemp = (new File
(recentlyConvertedFile.getAbsolutePath())).delete();
System.out.println("File deleted :: "+successtemp);*/
response.setContentType("application/octet-stream" );
response.setHeader("Content-Disposition","inline;filename=\"" + saveFile.getName() + "\"");
response.setContentLength((int) saveFile.length());
OutputStream os = response.getOutputStream();
FileInputStream fis = new FileInputStream(saveFile);
//op.write(response.toString().getBytes(Charset.forName("utf-8")));
//op.flush();
try {
int byteRead = 0;
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
// sends response to client
//response.getWriter().print("UPLOAD DONE");
}
The file is getting downloaded but not opening the generated pdf have the same size of the original and I have taken a text file and printed the content to another file it seems to read only first line of the text file taken as input
Your final loop returning a file from the servlet to the client looks like this:
while ((byteRead = fis.read()) != -1) {
os.write(buffer, 0, byteRead);
}
You seem to have forgotten to use buffer in the fis.read() which should look like this:
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
Thus, you send back as many copies of the buffer contents as fis returns numbers != -1.
BTW: Your servlet puts the data it receives into the ByteArrayOutputStream outputStream and drops that, but it claims to have written them into the file it eventually attempts to return to the caller.
I am new to Servlets and following Headfirst. It has an example to download jar file with mime type "application/jar". I changed it to "audio/mpeg3" to download an mp3 file. I get the player on the browser but it doesn't play. Here is the code:
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("audio/mpeg3");
ServletContext ctx=this.getServletContext();
InputStream is=ctx.getResourceAsStream("/RaOne.mp3");
int read=0;
byte[] bytes=new byte[1024];
OutputStream os=resp.getOutputStream();
while((read=is.read(bytes))!=-1)
{
os.write(bytes, 0, read);
}
os.flush();
os.close();
}
Can someone please help to figure out the problem?
you can try out something like this
ServletOutputStream stream = null;
BufferedInputStream buf = null;
try {
stream = response.getOutputStream();
File mp3 = new File("/myCollectionOfSongs" + "/" + fileName);
//set response headers
response.setContentType("audio/mpeg");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
response.setContentLength((int) mp3.length());
FileInputStream input = new FileInputStream(mp3);
buf = new BufferedInputStream(input);
int readBytes = 0;
//read from the file; write to the ServletOutputStream
while ((readBytes = buf.read()) != -1)
stream.write(readBytes);
} catch (IOException ioe) {
throw new ServletException(ioe.getMessage());
} finally {
if (stream != null)
stream.close();
if (buf != null)
buf.close();
}