[英]How do I use BufferedReader to put lines in an ArrayList and then execute them?
[英]How do you put the content of a BufferedReader into a String?
有沒有辦法將BufferedReader一次性放入String中,而不是逐行放置? 這是我到目前為止:
BufferedReader reader = null;
try
{
reader = read(filepath);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
String line = null;
String feed = null;
try
{
line = reader.readLine();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
while (line != null)
{
//System.out.println(line);
try
{
line = reader.readLine();
feed += line;
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println(feed);
您可以使用Apache FileUtils庫。
使用StringBuilder
和read(char[], int, int)
方法看起來像這樣,並且可能是在Java中執行它的最佳方式:
final MAX_BUFFER_SIZE = 256; //Maximal size of the buffer
//StringBuilder is much better in performance when building Strings than using a simple String concatination
StringBuilder result = new StringBuilder();
//A new char buffer to store partial data
char[] buffer = new char[MAX_BUFFER_SIZE];
//Variable holding number of characters that were read in one iteration
int readChars;
//Read maximal amount of characters avialable in the stream to our buffer, and if bytes read were >0 - append the result to StringBuilder.
while ((readChars = stream.read(buffer, 0, MAX_BUFFER_SIZE)) > 0) {
result.append(buffer, 0, readChars);
}
//Convert StringBuilder to String
return result.toString();
如果您知道輸入的長度(或它的上限),您可以使用read(char[],int,int)
將整個事物讀取到字符數組,然后使用它來構建String。 如果您的第三個參數( len
)大於該大小,則該方法將返回讀取的字符數。
使用Guava , CharStreams.toString(reader)
可以勝任。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.