我们可以通过创建一个StringBuffer或StringBuilder对象来逐个读取Reader中的字符,并将其拼接成一个完整的字符串。下面是一个示例代码: importjava.io.*;publicclassReaderToString{publicstaticStringreaderToString(Readerreader)throwsIOException{StringBufferstringBuffer=newStringBuffer();intdata;while((data=reader.read())...
importjava.io.StringReader;publicclassMain{publicstaticvoidmain(String[]args)throwsException{Stringtext="Hello, World!";StringReaderstringReader=newStringReader(text);Stringresult=ReaderToStringConverter.convertToString(stringReader);System.out.println(result);}} 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. ...
方法一:使用BufferedReader和StringBuilder 这是最常用的方法之一,通过BufferedReader逐行读取数据,然后使用StringBuilder来拼接字符串。 java import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; public class ReaderToString { public static String convert(Reader reader) throws IOException...
String line;//用来保存每行读取的内容BufferedReader reader =newBufferedReader(newInputStreamReader(is)); line= reader.readLine();//读取第一行while(line !=null) {//如果 line 为空说明读完了buffer.append(line);//将读到的内容添加到 buffer 中buffer.append("\n");//添加换行符line = reader.rea...
Reading file to byte array PathfilePath=Path.of("c:/temp/demo.txt");StringfileContent="";try{byte[]bytes=Files.readAllBytes(Paths.get(filePath));fileContent=newString(bytes);}catch(IOExceptione){//handle exception} 4. UsingBufferedReader– Java 6 ...
2、InputStream–>String inputStream input =null; StringBuffer out=newStringBuffer();byte[] b =newbyte[4096];for(intn; (n = input.read(b)) != -1;) { out.append(newString(b, 0, n)); }returnout.toString(); 3、Reader –>String ...
); BufferedReader bufferedReader = new BufferedReader(reader); StringBuffer sb = new StringBuffer(); String temp = null; while ((temp = bufferedReader.readLine()) != null) { sb.append(temp); } bufferedReader.close(); con.disconnect(); return sb....
String result = new BufferedReader(new InputStreamReader(inputStream)).lines().collect(Collectors.joining("\n"));使用 parallel Stream API (Java 8). 警告: 这个解决方案将不同的换行符(如\r\n)转换为\n。String result = new BufferedReader(new InputStreamReader(inputStream)).lines().parallel()....
参考链接: Java Reader类 1、String –> InputStream InputStrem is = new ByteArrayInputStream(str.getBytes()); 或者 ByteArrayInputStream stream= new ByteArrayInputStream(str.getBytes()); 2、InputStream–>String inputStream input; StringBuffer out = new StringBuffer(); ...
(fileReader);Stringline;while((line=bufferedReader.readLine())!=null){sb.append(line);sb.append("\n");}bufferedReader.close();returnsb.toString();}publicstaticvoidmain(String[]args){try{StringfilePath="path/to/file.txt";StringfileContent=readFileToString(filePath);System.out.println(file...