使用 java 创建 .gitignore
create .gitignore with java
我知道这个问题在某种意义上可能是重复的,但请先听我说完。
我试图创建一个代码,我可以在其中创建包含内容的 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 WhosebugMain {
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 或更高版本。
我知道这个问题在某种意义上可能是重复的,但请先听我说完。
我试图创建一个代码,我可以在其中创建包含内容的 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 WhosebugMain {
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 或更高版本。