java - 使用java创建.gitignore

标签 java gitignore

我知道这个问题在某种意义上可能是重复的,但请先听我说完。

我尝试创建一个代码,在其中可以创建包含内容的 gitignore 文件,但由于某种原因,我总是最终得到一个带有 txt 扩展名但没有名称的文件。有人可以解释这种行为以及原因吗?

示例代码:

System.out.println(fileDir+"\\"+".gitignore");
FileOutputStream outputStream = new FileOutputStream(fileDir+"\\"+".gitignore",false);
byte[] strToBytes = fileContent.getBytes();
outputStream.write(strToBytes);
outputStream.close();

最佳答案

您可以使用java.nio来实现它。请参阅以下示例:

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;

public class StackoverflowMain {

    public static void main(String[] args) {
        // create the values for a folder and the file name as Strings
        String folder = "Y:\\our\\destination\\folder";  // <-- CHANGE THIS ONE TO YOUR FOLDER
        String gitignore = ".gitignore";
        // create Paths from the Strings, the gitignorePath is the full path for the file
        Path folderPath = Paths.get(folder);
        Path gitignorPath = folderPath.resolve(gitignore);
        // create some content to be written to .gitignore
        List<String> lines = new ArrayList<>();
        lines.add("# folders to be ignored");
        lines.add("**/logs");
        lines.add("**/classpath");

        try {
            // write the file along with its content
            Files.write(gitignorPath, lines);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

它在我的 Windows 10 计算机上创建该文件没有任何问题。您需要 Java 7 或更高版本。

关于java - 使用java创建.gitignore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55256576/

相关文章:

Java String - 查看字符串是否仅包含数字而不包含字母

java - 如何在 java 中找到匿名类的 GC 根?

java - Android 空指针异常和无法在未调用 Looper.prepare() 的线程内创建处理程序

添加到 .gitignore 后,git 仍然显示已修改的文件

git - 如何在github中存储.env文件?

java - Redis 在运行时获取命令不可预测的结果

java - 如何使用递归编写链表的 contains 方法? java

Gitignore 双星模式不起作用

node.js - 推荐用于 Node-RED 的 .gitignore

xcode - gitignore 不忽略文件