It is necessary to read a text file from a stream, as it is done with a picture.
Important: reading in the OP and not in the file.
ZipInputStream zis; BufferedImage tmpImage; tmpImage = null; tmpImage = ImageIO.read(zis);
It is necessary to read a text file from a stream, as it is done with a picture.
Important: reading in the OP and not in the file.
ZipInputStream zis; BufferedImage tmpImage; tmpImage = null; tmpImage = ImageIO.read(zis);
Using only classes from the standard Java library, avoiding loops and other govnokoda does not work. Having an arbitrary InputStream, you can read the text as a string from it as follows:
import java.nio.charset.Charset; import java.io.*; static public String readTextFromInputStream(InputStream in, Charset cs) { StringBuilder text = new StringBuilder(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, cs)); String line = null; String newline = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { text.append(line); text.append(newline); } return text.toString(); }
Where the parameter cs means the intended encoding of the text. Use something like this:
String text = readTextFromInputStream(in, Charset.forName("CP1251"));
If you want to avoid all this govnokod, you have two options: either connect external libraries (for example, Apache Commons IO ), or use normal languages for JVM, for example, Scala , in which the solution will take one line:
def readFromInputStream(in: InputStream, cs: Codec) = Source.fromInputStream(in)(cs).mkString
Addition 1 . If you want to keep the splitting into strings, then we modify the original version of the readFromInputStream function as follows (so that it returns a list of strings):
import java.util.List; import java.util.ArrayList; static public List<String> readLinesFromInputStream(InputStream in, Charset cs) { List<String> lines = new ArrayList(); BufferedReader reader = new BufferedReader(new InputStreamReader(in, cs)); String line = null; String newline = System.getProperty("line.separator"); while ((line = reader.readLine()) != null) { lines.add(line + newline); } return lines; }
Source: https://ru.stackoverflow.com/questions/33813/
All Articles