Java 以字符串形式返回文件的文本?
可能重复:Java 以字符串形式返回文件的文本?,java,string,file,text,return,Java,String,File,Text,Return,可能重复: 是否可以处理多行文本文件并以字符串形式返回其内容 如果这是可能的,请告诉我怎么做 如果您需要更多信息,我正在使用I/O。我想打开一个文本文件,处理其内容,将其作为字符串返回,并将textarea的内容设置为该字符串 有点像文本编辑器。类似于 String result = ""; try { fis = new FileInputStream(file); bis = new BufferedInputStream(fis); dis = new DataInput
是否可以处理多行文本文件并以字符串形式返回其内容 如果这是可能的,请告诉我怎么做
如果您需要更多信息,我正在使用I/O。我想打开一个文本文件,处理其内容,将其作为字符串返回,并将textarea的内容设置为该字符串
有点像文本编辑器。类似于
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;
查看此处的java教程- 请记住首先导入java.io.*
这将用\n替换文件中的所有换行符,因为我认为没有任何方法可以在文件中使用分隔符。使用apache commons FileUtils的
StringBuffer
已被弃用。字符串串联以二次时间运行。改用StringBuilder
。虽然这是正确且最简单的方法,但这家伙是在“玩弄I/O”-所以这没有多大帮助。可能是真的。然而,他可以根据所指出的内容提取源代码并从中学习。没有必要在这里重新发明轮子,试图解释打开文件并将其内容读入字符串的无限不同方式。
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 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());
}