gpt4 book ai didi

java - 使用java创建.gitignore

转载 作者:行者123 更新时间:2023-11-30 01:53:30 25 4
gpt4 key购买 nike

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

我尝试创建一个代码,在其中可以创建包含内容的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com