0

I have a program where it searches for a file(it already has some content in it) based on the given directory path and lets the user add more content to that file. I was able to show all the files on the directory, but I am not sure how to select a file and write more content to it. Here is my code so far:

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();
    }

}
Nasim Ahmed
  • 235
  • 2
  • 17
  • http://stackoverflow.com/questions/1625234/how-to-append-text-to-an-existing-file-in-java will help with appending to the file once you get it – RAZ_Muh_Taz Sep 23 '16 at 17:50
  • since you can get the name of the files just append the name of the file to the current path you're using to get to your directory and use that when writing to the file – RAZ_Muh_Taz Sep 23 '16 at 17:52

2 Answers2

1

Example append to file:

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
}

Used - How to append text to an existing file in Java

Community
  • 1
  • 1
RAZ_Muh_Taz
  • 4,059
  • 1
  • 13
  • 26