2016-09-23 5 views
0

私は、指定されたディレクトリパスに基づいてファイルを検索し、そのファイルにコンテンツを追加させるプログラムを持っています。ディレクトリのすべてのファイルを表示できましたが、ファイルを選択してより多くのコンテンツを書き込む方法がわかりません。ここに私のコードは、これまでのところです:ファイルを検索してそのファイルに追加します

public static void main(String [] args) 
    { 

    // This shows all the files on the directory path 
    File dir = new File("/Users/NasimAhmed/Desktop/"); 
    String[] children = dir.list(); 
    if (children == null) 
    { 
     System.out.println("does not exist or is not a directory"); 
    } 
    else 
    { 
     for (int i = 0; i < children.length; i++) 
     { 
      String filename = children[i]; 
      System.out.println(filename); 
      // write content to sample.txt that is in the directory 
      out(dir, "sample.txt"); 
     } 
    } 
} 

public static void out(File dir, String fileName) 
{ 
    FileWriter writer; 

    try 
    { 
     writer = new FileWriter(fileName); 
     writer.write("Hello"); 
     writer.close(); 
    } 
    catch(IOException e) 
    { 
     e.printStackTrace(); 
    } 

} 
+0

http://stackoverflow.com/questions/1625234/how-to -append-text-to-existing-file-in-javaは、ファイルの名前を現在のパスに追加するだけで、ファイルを取得した後にファイルに追加するのに便利です –

+0

あなたは、あなたのディレクトリにアクセスするために使用してファイルに書き込むときにそれを使用する –

答えて

1

例は、ファイルに追加:

public static void appendToFile(File dir, String fileName) { 
    try (FileWriter writer = new FileWriter(new File(dir, fileName), true)) { 
     writer.write("Hello"); 
    } catch(IOException e) { 
     e.printStackTrace(); 
    } 
} 
0
// write content to sample.txt that is in the directory 
try { 
    Files.write(Paths.get("/Users/NasimAhmed/Desktop/" + filename), "the text".getBytes(), StandardOpenOption.APPEND); 
}catch (IOException e) { 
    //exception handling left as an exercise for the reader 
} 

が使用される - How to append text to an existing file in Java

関連する問題