1

I'm aware this question might be a duplicate in some sense but first hear me out.

I tried to create a code where i can create gitignore file with contents and for some reason i always end up having a file with txt extension and without name. Can someone explain this behavior and why?

Example Code:

System.out.println(fileDir+"\\"+".gitignore");
FileOutputStream outputStream = new FileOutputStream(fileDir+"\\"+".gitignore",false);
byte[] strToBytes = fileContent.getBytes();
outputStream.write(strToBytes);
outputStream.close();
  • Well yes i'm using windows. But does this mean i cant create anything on windows without extension? That would be pretty crappy from windows – Szilágyi István Mar 20 '19 at 08:45
  • 1
    On my Windows7 machine your code, using Java 8, created the desired ".gitignore". Maybe it depends on some Windows setting like "always display file extensions". See also https://stackoverflow.com/q/5004633/685806 – Pino Mar 20 '19 at 10:57
  • So yes it seems this is some sort of default window behavior. When i create a .gitignore the Name will be blank which is fine. But by default Windows 10 says thats a text document which tricked me for good. This does not affect the way my program works. Thanks for the help guys. – Szilágyi István Mar 20 '19 at 11:12

1 Answers1

2

You can use java.nio for it. See the following example:

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

It creates the file on my Windows 10 machine without any problems. You need Java 7 or higher for it.

deHaar
  • 17,687
  • 10
  • 38
  • 51
  • So yes it seems this is some sort of default window behavior. When i create a .gitignore the Name will be blank which is fine. But by default Windows 10 says thats a text document which tricked me for good. This does not affect the way my program works. Thanks for the help guys. – Szilágyi István Mar 20 '19 at 11:12