2015-12-17 17 views
-1

我有以下問題。在TXT文件Printstream上的錯誤。只有最後的聲明ist寫

``` 
1 3 1. 
``` 

實際上是字符串變量打印,它必須輸出

``` 
1 1 1 
1 2 1 
1 3 1 
``` 

我不知道,這裏的錯誤是在代碼。這似乎是代碼每次都被覆蓋,最後一條語句被覆蓋。任何人都可以幫助我

public class RankingExportTest { 
private static final String LINE_SEPARATOR = "\r\n"; 
Set<String> exportGraph(DirectedUnweightedGraph<CommonNode, CommonEdge<CommonNode>> graph) throws IOException { 
Set<String> rows = new LinkedHashSet<>((int)graph.getEdgeCount()); 
for(CommonNode fromNode: graph.getNodes()) { 
for(CommonNode toNode: graph.adjacentTo(fromNode)) { 
      String row = String.format(
       "%d %d 1", 
       fromNode.getIdentity().intValue(), 
       toNode.getIdentity().intValue() 
      ); 
      rows.add(row); 
      System.out.println(row); 

      try { 
       PrintWriter out; 
       out = new PrintWriter("/Users/......"); 
       out.print(rows); 
       out.close(); 
       //System.out.println(row); 
      } catch (FileNotFoundException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return rows; 

} 
+0

是否可以用覆蓋模式打開文件而不是追加內容?嘗試從這裏的解決方案: [可能的副本](http://stackoverflow.com/questions/14443662/printwriter-add-text-to-file) –

回答

0

您可以打開和關閉PrintWriter在循環的每次迭代,每次覆蓋文件。在循環之前打開它並關閉它。

0

您正在用每一行覆蓋文件。創建PrintWriter一次,寫入所有輸出,然後關閉它:

PrintWriter out = null; 
try { 
    out = new PrintWriter("path"); 
    for (CommonNode fromNode : graph.getNodes()) { 
     for (CommonNode toNode : graph.adjacentTo(fromNode)) { 
      String row = String.format("%d %d 1", fromNode.getIdentity().intValue(), toNode.getIdentity().intValue()); 
      rows.add(row); 
      System.out.println(row); 
      out.print(row); 
     } 
    } 
} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} finally { 
    if (out != null) { 
     out.close(); 
    } 
} 
+0

Thx,但是當我使用這種方法,我得到錯誤AVA: 43:錯誤:變量輸出可能未被初始化 out.close(); –

+0

@OkanAlbayrak這是由於沒有處理異常造成的,請立即嘗試。 – Keammoort

+0

好的,我已修復。您只能將該語句放在=新的PrintWriter(「/ Users/......」);以上 –