создать .gitignore с Java - PullRequest
0 голосов
/ 20 марта 2019

Я знаю, что этот вопрос может быть в некотором смысле дубликатом, но сначала выслушайте меня.

Я пытался создать код, в котором я могу создать файл gitignore с содержимым, и по какой-то причине я всегда получаюимеющий файл с расширением txt и без имени.Может кто-нибудь объяснить это поведение и почему?

Пример кода:

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

1 Ответ

1 голос
/ 20 марта 2019

Вы можете использовать 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 или выше.

...