2011-03-08 35 views

回答

0

檢查這裏的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

0

沿

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

0
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替換文件中的所有換行符,因爲我不認爲有任何方法可以獲取文件中使用的分隔符。

2

使用apache-commons FileUtils的readFileToString

+0

儘管正確並且最簡單的方法是,那傢伙「正在玩I/O」 - 所以這沒有多大幫助。 – 2011-03-09 00:42:08

+0

可能是真的。但是,他可以根據所指出的內容並從中吸取教訓。這裏不需要重新發明輪子,試圖解釋打開文件並將其內容讀入字符串的無限不同方式。 – rfeak 2011-03-09 01:01:44

相關問題