i m new in java....i m trying to read a text file using file input stream. i m reading text line by line and set as a string.. now i want to convert string into byte. but i m getting a number format exception.. please help me to solve this problem.
FileInputStream fstream = new FileInputStream("C:/Users/data.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte[] bytes = null;
String str;
int i=0;
while ((str = br.readLine()) != null)
{
bytes[i] = Byte.parseByte(str,16);
i++;
}
in.close();
Try
byte[] bytes = str.getBytes();
instead of
bytes[i] = Byte.parseByte(str,16);
Also I recommend to specify encoding for InputStreamReader:
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
Keep in mind that Java String length and internal representation would not be same to C.
You can simply use the getBytes() method from the String class :
str.getBytes()
Or if you don't use the default character set :
str.getBytes(myCharSet);
you can use,
str.getBytes() which will convert the string into the byte array.
you can try this code.
fstream = new FileInputStream("C:/Users/s.hussain/Desktop/test3.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
byte[] bytes = null;
String str;
int i=0;
while ((str = br.readLine()) != null)
{
bytes = str.getBytes();
i++;
System.out.println(bytes.length);
}
in.close();
Related
I am creating this method which takes an InputStream as parameter, but the readLine() function is returning null. While debugging, inputstream is not empty.
else if (requestedMessage instanceof BytesMessage) {
BytesMessage bytesMessage = (BytesMessage) requestedMessage;
byte[] sourceBytes = new byte[(int) bytesMessage.getBodyLength()];
bytesMessage.readBytes(sourceBytes);
String strFileContent = new String(sourceBytes);
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(sourceBytes);
InputStream inputStrm = (InputStream) byteInputStream;
processMessage(inputStrm, requestedMessage);
}
public void processMessage(InputStream inputStrm, javax.jms.Message requestedMessage) {
String externalmessage = tradeEntryTrsMessageHandler.convertInputStringToString(inputStrm);
}
public String convertInputStringToString(InputStream inputStream) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
br.close();
return sb.toString();
}
Kindly try this,
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
i believe that raw data as it is taken is not formatted to follow a character set. so by mentioning UTF-8 (U from Universal Character Set + Transformation Format—8-bit might help
Are you sure you are initializing and passing a valid InputStream to the function?
Also, just FYI maybe you were trying to name your function convertInputStreamToString instead of convertInputStringToString?
Here are two other ways of converting your InputStream to String, try these maybe?
1.
String theString = IOUtils.toString(inputStream, encoding);
2.
public String convertInputStringToString(InputStream is) {
java.util.Scanner s = new java.util.Scanner(is, encoding).useDelimiter("\\A");
return s.hasNext() ? s.next() : "";
}
EDIT:
You needn't explicitly convert ByteArrayInputStream to InputStream. You could do directly:
InputStream inputStrm = new ByteArrayInputStream(sourceBytes);
I tried putting a toast before the return statement but the String variable returns an empty string.
public String getXmlFile(String pathFile, Context context){
String xmlFileString = "";
AssetManager am = context.getAssets();
try {
InputStream str = am.open(pathFile);
int length = str.available();
byte[] data = new byte[length];
xmlFileString = new String(data);
} catch (IOException e1) {
e1.printStackTrace();
}
return xmlFileString;
}
use this to read byte[] from InputStream:
public byte[] convertStreamToString(InputStream is) throws Exception {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
is.close();
return sb.toString().getBytes("UTF-8");
}
Use this to read the XML. Without passing UTF-8 to the InputStreamReader you might get a broken XML string.
BufferedReader reader = new BufferedReader(new InputStreamReader(
context.getAssets().open(pathFile), HTTP.UTF_8));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
Now when parsing the string to XML in my case there was also the problem that each line break was interpreted as an own XML node. Spaces also were an issue. Use this on the string read above to fix that:
String oneLineXml = sb.toString().replace("\n", "").replaceAll("> +<", "><");
Only then you should parse the string, like this:
Document xml = DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new ByteArrayInputStream(
oneLineXml.getBytes(HTTP.UTF_8))));
URL u = new URL(url);
String expected = "";
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r= new InputStreamReader(in);
so here is my code and i want a very little help that is the above is to fetch the content from url but now i want to use the same code for reading content from file what i need to change in above code....i mean there should be something which i need to change in the place of uc.getInputStream()...so what is that
InputStream in = new BufferedInputStream(uc.getInputStream());
Look at class FileInputStream.
You can simply user that code and do it in similar way.
InputStream in = new FileInputStream(new File("C:/temp/test.txt"));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder out = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
out.append(line);
}
System.out.println(out.toString()); //Prints the string content read from input stream
reader.close();
I am reading a request body and put it into an input stream. While I am explicitly saying the decode method, I still get many \u0000 (Null) after the string.
InputStream is = exchange.getRequestBody();
byte[] header = new byte[100];
is.read(header);
String s = new String(header, "UTF-8");
How can I avoid this with Standard Java Library? I cannot use third party libraries.
is.read(header); returns the number of bytes that were actually read. Change your code as
byte[] header = new byte[100];
int n = is.read(header);
String s = new String(header, 0, n, "UTF-8");
Try using BufferedReader with InputStreamReader. I.e.
InputStreamReader isr = new InputStreamReader(is, "UTF-8");
BufferedReader br = new BufferedReader(isr);
String line = br.readLine();
Use a buffered reader to read it line by line:
InputStream is = exchange.getRequestBody();
BufferedReader reader = new BufferedReader(new InputStreamReader(is))
String line;
while((line = reader.readLine()) != null)
{
// do work
}
If you look at the value of line.toCharArray(), you will see that the null (aka '\u0000') chars show up. A round-about solution to getting rid of those is to add only the chars that you want to another array by using an if statement to exclude the '\u0000' chars. So:
public String removeNullChars(String line) {
String result = "";
// Convert to char array.
char[] chars = line.toCharArray();
// Add only chars that are not equal to '\u0000' to result
for (int i = 0; i < chars.length; i++) {
if (chars[i] != '\u0000') {
result += chars[i];
}
}
return result;
}
I'm loading an XML file with this method:
public static String readTextFile(String fullPathFilename) throws IOException {
StringBuffer sb = new StringBuffer(1024);
BufferedReader reader = new BufferedReader(new FileReader(fullPathFilename));
char[] chars = new char[1024];
while(reader.read(chars) > -1){
sb.append(String.valueOf(chars));
}
reader.close();
return sb.toString();
}
But it doesn't load the whole data. Instead of 25634 characters, it loads 10 less (25624). Why is that?
Thanks,
Ivan
With BufferedReader you get the readLine()-Method, which works well for me.
StringBuffer sb = new StringBuffer( 1024 );
BufferedReader reader = new BufferedReader( new FileReader( fullPathFilename ) );
while( true ) {
String line = reader.readLine();
if(line == null) {
break;
}
sb.append( line );
}
reader.close();
I think there's a bug in your code, the last read might not necessarily fill the char[], but you still load the string with all of it. To account for this you need to do something like:
StringBuilder res = new StringBuilder();
InputStreamReader r = new InputStreamReader(new BufferedInputStream(is));
char[] c = new char[1024];
while(true) {
int charCount = r.read(c);
if (charCount == -1) {
break;
}
res.append(c, 0, charCount);
}
r.close();
Also, how do you know you're expecting 25634 chars?
(and use StringBuilder instead of StringBuffer, the former is not threadsafe so sightly faster)
Perhaps you have 25634 Bytes in your file that represent only 25624 Characters? This might happen with multibyte character sets like UTF-8. All InputStreamReader (including FileReader) automatically do this conversion using a Charset (either an explicitly given one, or the default encoding that depends on the platform).
Use FileInputStream to avoid certain characters getting recognized as utf-8:
StringBuffer sb = new StringBuffer(1024);
FileInputStream fis = new FileInputStream(filename);
char[] chars = new char[1024];
while(reader.read(chars) > -1){
sb.append(String.valueOf(chars));
}
fis.close();
return sb.toString();