I have a String[] array and I need to convert it to InputStream.
I've seen Byte[] -> InputStream and String -> InputStream, but not this. Any tips?
You can construct a merged String with some separator and then to byte[] and then to ByteArrayInputStream.
Here's a way to convert a String to InputStream in Java.
Have a look at the following link: http://www.mkyong.com/java/how-to-convert-string-to-inputstream-in-java/
However, the difference in the code is that you should concatenate all the strings together in one string before converting.
String concatenatedString = ... convert your array
// convert String into InputStream
InputStream is = new ByteArrayInputStream(str.getBytes());
// read it with BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
There is still no single method call to do this but with Java 8 you can do it in a single line of code. Given an array of String objects:
String[] strings = {"string1", "string2", "string3"};
You can convert the String array to an InputStream using:
InputStream inputStream = new ByteArrayInputStream(String.join(System.lineSeparator(), Arrays.asList(strings)).getBytes(StandardCharsets.UTF_8));
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'm looking for a way to switch between reading bytes (as byte[]) and reading lines of Strings from a file. I know that a byte[] can be obtained form a file through a FileInputStream, and a String can be obtained through a BufferedReader, but using both of them at the same time is proving problematic. I know how long the section of bytes are. String encoding can be kept constant from when I write the file. The filetype is a custom one that is still in development, so I can change how I write data to it.
How can I read Strings and byte[]s from the same file in java?
Read as bytes. When you have read a sequence of bytes that you know should be a string, place those bytes in an array, put the array inside a ByteArrayInputStream and use that as the underlying InputStream for a Reader to get the bytes as characters, then read those characters to produce a String.
For the later parts of this process see the related SO question on how to create a String from an InputStream.
Read the file as Strings using a BufferedReader then use String.getBytes().
Why not try this:
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("testing.txt"));
String line = bufferedReader.readLine();
while(line != null){
byte[] b = line.getBytes();
}
} finally {
if(bufferedReader!=null){
bufferedReader.close();
}
}
or
FileInputStream in = null;
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new FileReader("xanadu.txt"));
String line = bufferedReader.readLine();
while(line != null){
//read your line
}
in = new FileInputStream("xanadu.txt");
int c;
while ((c = in.read()) != -1) {
//read your bytes (c)
}
} finally {
if (in != null) {
in.close();
}
if(bufferedReader!=null){
bufferedReader.close();
}
}
Read everything as bytes from the buffered input stream, and convert string sections into String's using constructor that accepts the byte array:
String string = new String(bytes, offset, length, "US-ASCII");
Depending on how the data are actually encoded, you may need to use "UTF-8" or something else as the name of the charset.
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();
I want to copy http://docs.oracle.com/javase/tutorial/collections/interfaces/examples/dictionary.txt into an array for hangman game. I have this so far..
url = new URL("http://docs.oracle.com/javase/tutor… );
urlConn = url.openConnection();
urlConn.getInputStream());
inStream in = new InputStreamReader("dictionary.txt");
urlConn.getInputStream());
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String nextLine;
String[] secretwordbank;
secretwordbank = new String[80368];
secretwordbank is an array representing a dictionary of words. This may be too big of an array so I'm open for ideas to optimize it. Anyone know how to do it?
Are you really just unsure how to convert a BufferedReader into an array (or other collection) of strings, based on line breaks? If so, I'd suggest using Guava:
List<String> lines = CharStreams.readLines(reader);
(As an aside, I would suggest specifying an encoding when creating the InputStreamReader - otherwise it will use the platform default encoding. Ideally, you should use the content-type header from the response to determine the encoding... there are higher-level HTTP libraries which will do all of this for you, such as HttpClient.)
Use this Java code to build your list of words:
URL url = new URL("http://docs.oracle.com/javase/tutorial/collections/interfaces/examples/dictionary.txt");
URLConnection urlConn = url.openConnection();
InputStream in = urlConn.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String nextLine;
List<String> secretwordbank = new ArrayList<String>();
while ((nextLine = br.readLine()) != null) {
secretwordbank.add(nextLine);
}
System.out.println("Secret Word List: " + secretwordbank);
Edit: If you're looking to have an array of String rather than a List<String>
String[] wordBankArr = secretwordbank.toArray(new String[0]);
System.out.println("Secret Word Array: " + Arrays.toString(wordBankArr));
My input is a InputStream which contains an XML document. Encoding used in XML is unknown and it is defined in the first line of XML document.
From this InputStream, I want to have all document in a String.
To do this, I use a BufferedInputStream to mark the beginning of the file and start reading first line. I read this first line to get encoding and then I use an InputStreamReader to generate a String with the correct encoding.
It seems that it is not the best way to achieve this goal because it produces an OutOfMemory error.
Any idea, how to do it?
public static String streamToString(final InputStream is) {
String result = null;
if (is != null) {
BufferedInputStream bis = new BufferedInputStream(is);
bis.mark(Integer.MAX_VALUE);
final StringBuilder stringBuilder = new StringBuilder();
try {
// stream reader that handle encoding
final InputStreamReader readerForEncoding = new InputStreamReader(bis, "UTF-8");
final BufferedReader bufferedReaderForEncoding = new BufferedReader(readerForEncoding);
String encoding = extractEncodingFromStream(bufferedReaderForEncoding);
if (encoding == null) {
encoding = DEFAULT_ENCODING;
}
// stream reader that handle encoding
bis.reset();
final InputStreamReader readerForContent = new InputStreamReader(bis, encoding);
final BufferedReader bufferedReaderForContent = new BufferedReader(readerForContent);
String line = bufferedReaderForContent.readLine();
while (line != null) {
stringBuilder.append(line);
line = bufferedReaderForContent.readLine();
}
bufferedReaderForContent.close();
bufferedReaderForEncoding.close();
} catch (IOException e) {
// reset string builder
stringBuilder.delete(0, stringBuilder.length());
}
result = stringBuilder.toString();
}else {
result = null;
}
return result;
}
The call to mark(Integer.MAX_VALUE) is causing the OutOfMemoryError, since it's trying to allocate 2GB of memory.
You can solve this by using an iterative approach. Set the mark readLimit to a reasonable value, say 8K. In 99% of cases this will work, but in pathological cases, e.g 16K spaces between the attributes in the declaration, you will need to try again. Thus, have a loop that tries to find the encoding, but if it doesn't find it within the given mark region, it tries again, doubling the requested mark readLimit size.
To be sure you don't advance the input stream past the mark limit, you should read the InputStream yourself, upto the mark limit, into a byte array. You then wrap the byte array in a ByteArrayInputStream and pass that to the constructor of the InputStreamReader assigned to 'readerForEncoding'.
You can use this method to convert inputstream to string. this might help you...
private String convertStreamToString(InputStream input) throws Exception{
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
input.close();
return sb.toString();
}