可以将文章内容翻译成中文,广告屏蔽插件会导致该功能失效:
问题:
I can read the first line from the input stream and store it into string variable.Then how do i read remaining lines and copy to the another input stream to process further.
InputStream is1=null;
BufferedReader reader = null;
String todecrypt = null;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
todecrypt = reader.readLine(); // this will read the first line
String line1=null;
while ((line1 = reader.readLine()) != null){ //loop will run from 2nd line
is1 = new ByteArrayInputStream(line1.getBytes());
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
System.out.println("to decrpt str==="+todecrypt);
then i will use is1 as anothor inputstream from second line and my sample file sending here
回答1:
Expanding Jerry Chin's comment into a full answer:
you can just do
BufferedReader reader = null;
String todecrypt = null;
try {
reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
todecrypt = reader.readLine(); // this will read the first line
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
System.out.println("to decrpt str==="+todecrypt);
//This will output the first character of the second line
System.out.println((char)inputStream.read());
You can imagine an Inputstream as a row of characters. Reading a character is removing the first character in the row. After that you can still use the Inputstream to read more characters. The BufferedReader just reads the InputStream until it finds a 'n'.
回答2:
Because you are using readers (BufferedReader and InputStreamReader) they read data from original stream (inputStream variable) as chars, not as bytes. So after you read first line from reader original stream will be empty. It's because reader will try to fill whole char buffer (by default it's defaultCharBufferSize = 8192 chars). So you really can't use original stream anymore, because it has no data anymore. You have to read remaining chars from existing reader, and create a new InputStream with remaining data. Code example below:
public static void main(String[] args) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream("line 1 rn line 2 rn line 3 rn line 4".getBytes());
BufferedReader reader = new BufferedReader(new InputStreamReader(bais));
System.out.println(reader.readLine());
StringBuilder sb = new StringBuilder();
int c;
while ((c = reader.read()) > 0)
sb.append((char)c);
String remainder = sb.toString();
System.out.println("`" + remainder + "`");
InputStream streamWithRemainingLines = new ByteArrayInputStream(remainder.getBytes());
}
Note that rn's aren't lost