1

How can I create and read folders in Java when using UTF-8 characters? Currently the 'ä'-character in my folder named "strängePath" are getting replaced with '?'. Any hints on where to find a solution?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

public class ReadFilePath {
    public static void main(String[] args) {

        // Create folder and file: [Project]/strängePath/tmp.txt
        String homePath = System.getProperty("user.dir");
        String dirPath = createDirectory("strängePath", homePath);
        String path = createFile("tmp.txt", dirPath);

        // Try to read the created "tmp.txt" file
        try {
            new FileInputStream(path);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    private static String createDirectory(String dirName, String path) {
        String dirPath = path + "/" + dirName;
        File file = new File(dirPath);
        System.out.println("Created folder: " + dirPath + " -> " + file.mkdir());
        return dirPath;
    }

    private static String createFile(String fileName, String path) {
        String filePath = path + "/" + fileName;
        File file = new File(filePath);
        try {
            System.out.println("Created file: " + filePath + " -> " + file.createNewFile());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filePath;
    }
}
Grains
  • 950
  • 3
  • 16
  • 35

1 Answers1

0

I think the issue is caused by the encoding of the source file: it is different from the encoding of the system. If your file is saved using UTF-8 but you are in Windows, the "hardcoded" text will be UTF-8 but Windows does not use that.

Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59