可能重複:
How to create a Java String from the contents of a file以字符串形式返回文件的文本?
是否可以處理多行文本文件,並作爲一個字符串返回其內容是什麼?
如果這是可能的,請告訴我如何。
如果你需要更多信息,我與I/O玩耍。我想打開一個文本文件,處理它的內容,將它作爲一個String返回,並將textarea的內容設置爲該字符串。
有點像文本編輯器。
可能重複:
How to create a Java String from the contents of a file以字符串形式返回文件的文本?
是否可以處理多行文本文件,並作爲一個字符串返回其內容是什麼?
如果這是可能的,請告訴我如何。
如果你需要更多信息,我與I/O玩耍。我想打開一個文本文件,處理它的內容,將它作爲一個String返回,並將textarea的內容設置爲該字符串。
有點像文本編輯器。
檢查這裏的Java教程東西線 - http://download.oracle.com/javase/tutorial/essential/io/file.html
Path file = ...;
InputStream in = null;
StringBuffer cBuf = new StringBuffer();
try {
in = file.newInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
cBuf.append("\n");
cBuf.append(line);
}
} catch (IOException x) {
System.err.println(x);
} finally {
if (in != null) in.close();
}
// cBuf.toString() will contain the entire file contents
return cBuf.toString();
沿
String result = "";
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0) {
// Here's where you get the lines from your file
result += dis.readLine() + "\n";
}
fis.close();
bis.close();
dis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return result;
字符串串聯以二次方式運行。改用'StringBuilder'。 – 2011-03-08 23:38:29
String data = "";
try {
BufferedReader in = new BufferedReader(new FileReader(new File("some_file.txt")));
StringBuilder string = new StringBuilder();
for (String line = ""; line = in.readLine(); line != null)
string.append(line).append("\n");
in.close();
data = line.toString();
}
catch (IOException ioe) {
System.err.println("Oops: " + ioe.getMessage());
}
只記得import java.io.*
第一。
這將用\ n替換文件中的所有換行符,因爲我不認爲有任何方法可以獲取文件中使用的分隔符。
使用apache-commons FileUtils的readFileToString
儘管正確並且最簡單的方法是,那傢伙「正在玩I/O」 - 所以這沒有多大幫助。 – 2011-03-09 00:42:08
可能是真的。但是,他可以根據所指出的內容並從中吸取教訓。這裏不需要重新發明輪子,試圖解釋打開文件並將其內容讀入字符串的無限不同方式。 – rfeak 2011-03-09 01:01:44
'StringBuffer'已棄用你知道。 – 2011-03-08 23:37:43