2014-11-08 161 views
0

我正尝试使用通过命令行运行配置给出的原始路径写入文件。不过,我很难将这些部分放在一起。我试图通过Report类构造函数传递文件名,然后使用它来使用打印方法写入文件。我究竟做错了什么?对不起,我对java很不好...如何通过命令行向文本文件写入文件?

public static void main(String[] args) throws IOException { 
     String roadFilename = args[0]; 
     String cellNetworkFilename = args[1]; 
     String imageFilename = args[2]; 
     String reportFilename = args[3]; 

    Report report = new Report( 
       new java.io.File(reportFilename) 
       ); 
     report.add(message); 
     report.write(); 
     cellNetwork.hasCoverage(roadNetwork); 
    } 


public class Report { 
    String mess; 
    java.util.ArrayList<String> something = new java.util.ArrayList<String>(); 
    File file; 
    private PrintWriter print; 
    public Report(File file) { 


     this.file=file; 
     // TODO Auto-generated constructor stub 
    } 

    public void add(String message) { 

     something.add(message); 

    public void write() { 


     try { 
      print = new PrintWriter( 
        new BufferedWriter(
          new FileWriter(file))); 
      print.println(something); 

     } catch (IOException e) { 
      // TODO Auto-generated catch block 
      //   e.printStackTrace(); 
      System.exit(0); 
     } 
+0

1)为什么不关闭文件?2)为什么'e.printStackTrace();'注释掉了? – immibis 2014-11-08 08:18:06

回答

0

您需要打印ArrayList的内容,它包含您添加的消息。不是ArrayList本身。试图像这样打印:

print.println(something); 

将导致指针字符串被打印到文件而不是内容。

您可能需要遍历数组列表并逐行打印其内容。

for(String string: something) { 
    print.println(string); 
} 
0

您忘记关闭最后的PrintWriter。

try { 
    print = new PrintWriter(new BufferedWriter(new FileWriter(file))); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
if(print != null) { 
    print.println(something); 
    print.close(); 
} 
相关问题