Nasim Ahmed Nasim Ahmed - 2 months ago 9
Java Question

Search for a file and append to it

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

}

Answer

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