java - 搜索文件并附加到该文件

标签 java file-io

我有一个程序,它根据给定的目录路径搜索文件(其中已经有一些内容),并允许用户向该文件添加更多内容。我能够显示目录中的所有文件,但我不确定如何选择文件并向其写入更多内容。这是到目前为止我的代码:

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

}

最佳答案

附加到文件的示例:

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

关于java - 搜索文件并附加到该文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39666682/

相关文章:

java - org.openqa.selenium.SessionNotCreatedException : A new session could not be created.(原始错误:请求了一个新 session ,但一个正在进行中)

java - 复制或合并两个包含相同对象的 ArrayList 的有效方法

java - Dexguard 在 Ant 调试构建期间运行?

java - JSON、XML 或字符串连接

c++ - 流的 fscanf 类型函数?

java - Java (Linux) 中的文件路径

c++ - 使用ofstream缓冲文本输出以获得性能

Java 套接字(Android 到 Java 服务器)

mysql - SELECT INTO OUTFILE 两个表有条件错误

java - android 内部存储写入文件后没有文件