以字符串形式返回文件的文本?

问题描述:

可能重复:
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(); 
+2

'StringBuffer'已弃用你知道。 – 2011-03-08 23:37:43

沿

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; 
+2

字符串串联以二次方式运行。改用'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

+0

尽管正确并且最简单的方法是,那家伙“正在玩I/O” - 所以这没有多大帮助。 – 2011-03-09 00:42:08

+0

可能是真的。但是,他可以根据所指出的内容并从中吸取教训。这里不需要重新发明*,试图解释打开文件并将其内容读入字符串的无限不同方式。 – rfeak 2011-03-09 01:01:44