Just wondering if my bufferedWrites will work outside this try clause as it should as. i atm have no way of checking the outcome atm but. As in i only need the stream to be open for the instantiation of the BufferedWriter correct.
So this code should work:
BufferedWriter bufferedWriter;
// ServletOutputStream responseOutputStream = null;
FileOutputStream fos = new FileOutputStream(file);
if (zip) {
try (ZipOutputStream zOut = new ZipOutputStream(fos);) {
String fileName = file.getName().replace(".zip", "");
zOut.putNextEntry(new ZipEntry(fileName));
bufferedWriter = new BufferedWriter(new OutputStreamWriter(zOut, Charset.forName(enc)));
}
} else {
try (OutputStreamWriter opsw = new OutputStreamWriter(fos, Charset.forName(enc))) {
bufferedWriter = new BufferedWriter(opsw);
}
}
File fin = new File(tempFile);
FileInputStream fis = new FileInputStream(fin);
BufferedReader bufferedReader;
try(InputStreamReader ipsr = new InputStreamReader(fis)){
bufferedReader = new BufferedReader(ipsr);
}
String aLine = null;
int rowCount = 1;
logger.info("Copy file for output");
while ((aLine = bufferedReader.readLine()) != null) {
if (rowCount == 1) {
// Ful fix wax klarar nog inte att s�tta encoding.
if (encoding.equals(ProductFeedOutputController.ENCODING_88591)) {
bufferedWriter.write("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>");
} else {
bufferedWriter.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
}
......
I have a outlook where I have to read subject and body content of the mail in java. Everything works fine, but if I have body with screenshot it throws ERROR: invalid byte sequence for encoding "UTF8": 0x00
I have tried to put the mail as a doc attachment. But no use.
String destFilePath = path + ticketId + "/" + bpFileName;
File f = new File(path + ticketId);
if (!f.exists()) {
f.mkdirs();
}
InputStream input = bp.getInputStream();
byte[] buffer = new byte[4096];
int bytRead = -1;
byte[] byteRead = new byte[4096];
while ((bytRead = input.read(byteRead)) != -1) {
if (byteRead != null) {
String content2 = new String(byteRead, "us-ascii");
if (content2 != null) {
content = content.concat(content2);
}
}
}
input.close();
Expected is text or html content. But it gives xml,html,text, invalid byte sequence exception.
I want to extract and save an incoming ZipFile from the Server.
This code works only half of the time.
InputStream is = socket.getInputStream();
zipStream = new ZipInputStream(new BufferedInputStream(is);
ZipEntry entry;
while ((entry = zipStream.getNextEntry()) != null) {
String mapPaths = MAPFOLDER + entry.getName();
Path path = Paths.get(mapPaths);
if (Files.notExists(path)) {
fileCreated = (new File(mapPaths)).mkdirs();
}
String outpath = mapPaths + "/" + entry.getName();
FileOutputStream output = null;
try {
output = new FileOutputStream(outpath);
int len = 0;
while ((len = zipStream.read(buffer)) > 0) {
output.write(buffer, 0, len);
}
} finally {
if (output != null)
output.close();
}
}
I think the problem is, that the method zipStream.getNextEntry() gets called before the data is incoming, how can I wait for incoming data to read?
I'm reading a response from an HttpURLConnection object to a String like so:
HttpURLConnection conn = ...;
BufferedReader rd = new BufferedReader(new InputStreamReader(
conn.getInputStream());
StringBuilder sb = ...;
String line = "";
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String asString = sb.toString();
If I want to read instead to a byte array first, then convert that byte array to a String, what's the right way to do it?
InputStream is = conn.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream(16384);
byte[] buf = new byte[512];
while (true) {
int len = in.read(buf);
if (len == -1) {
break;
}
baos.write(buf, 0, len);
}
byte[] out = baos.toByteArray();
// as a string:
String asString = new String(out);
but I'm not specifying the character in either case - are the two String outputs at the end of the examples equivalent?
Thanks
In my java project, I'm passing FileInputStream to a function,
I need to convert (typecast FileInputStream to string),
How to do it.??
public static void checkfor(FileInputStream fis) {
String a=new String;
a=fis //how to do convert fileInputStream into string
print string here
}
You can't directly convert it to string. You should implement something like this
Add this code to your method
//Commented this out because this is not the efficient way to achieve that
//StringBuilder builder = new StringBuilder();
//int ch;
//while((ch = fis.read()) != -1){
// builder.append((char)ch);
//}
//
//System.out.println(builder.toString());
Use Aubin's solution:
public static String getFileContent(
FileInputStream fis,
String encoding ) throws IOException
{
try( BufferedReader br =
new BufferedReader( new InputStreamReader(fis, encoding )))
{
StringBuilder sb = new StringBuilder();
String line;
while(( line = br.readLine()) != null ) {
sb.append( line );
sb.append( '\n' );
}
return sb.toString();
}
}
public static String getFileContent(
FileInputStream fis,
String encoding ) throws IOException
{
try( BufferedReader br =
new BufferedReader( new InputStreamReader(fis, encoding )))
{
StringBuilder sb = new StringBuilder();
String line;
while(( line = br.readLine()) != null ) {
sb.append( line );
sb.append( '\n' );
}
return sb.toString();
}
}
Using Apache commons IOUtils function
import org.apache.commons.io.IOUtils;
InputStream inStream = new FileInputStream("filename.txt");
String body = IOUtils.toString(inStream, StandardCharsets.UTF_8.name());
Don't make the mistake of relying upon or needlessly converting/losing endline characters. Do it character by character. Don't forget to use the proper character encoding to interpres the stream.
public String getFileContent( FileInputStream fis ) {
StringBuilder sb = new StringBuilder();
Reader r = new InputStreamReader(fis, "UTF-8"); //or whatever encoding
int ch = r.read();
while(ch >= 0) {
sb.append(ch);
ch = r.read();
}
return sb.toString();
}
If you want to make this a little more efficient, you can use arrays of characters instead, but to be honest, looping over the characters can be still quite fast.
public String getFileContent( FileInputStream fis ) {
StringBuilder sb = new StringBuilder();
Reader r = new InputStreamReader(fis, "UTF-8"); //or whatever encoding
char[] buf = new char[1024];
int amt = r.read(buf);
while(amt > 0) {
sb.append(buf, 0, amt);
amt = r.read(buf);
}
return sb.toString();
}
From an answer I edited here:
static String convertStreamToString(java.io.InputStream is) {
if (is == null) {
return "";
}
java.util.Scanner s = new java.util.Scanner(is);
s.useDelimiter("\\A");
String streamString = s.hasNext() ? s.next() : "";
s.close();
return streamString;
}
This avoids all errors and works well.
Use following code ---->
try {
FileInputStream fis=new FileInputStream("filename.txt");
int i=0;
while((i = fis.read()) !=-1 ) { // to reach until the laste bytecode -1
System.out.print((char)i); /* For converting each bytecode into character */
}
fis.close();
} catch(Exception ex) {
System.out.println(ex);
}