How can I open files containing accents in Java?

前端 未结 6 1634
傲寒
傲寒 2020-12-01 18:44

(editing for clarification and adding some code)

Hello, We have a requirement to parse data sent from users all over the world. Our Linux systems have a de

6条回答
  •  一向
    一向 (楼主)
    2020-12-01 19:23

    Well I was strangled with this issue all the day! My previous (wrong) code was the same as you:

    for(File f : dir.listFiles()) {
     String filename = f.getName(); // The filename here is wrong !
     FileInputStream fis = new FileInputStream (filename);
    }
    

    and it does not work (I'm using Java 1.7 Oracle on CentOS 6, LANG and LC_CTYPE=fr_FR.UTF-8 for all users except zimbra => LANG and LC_CTYPE=C - which btw is certainly the cause of this issue but I can't change this without the risk that Zimbra stops working...)

    So I decided to use the new classes of java.nio.file package (Files and Paths):

    DirectoryStream paths = Files.newDirectoryStream(Paths.get(outputName));
    for (Iterator iterator = paths.iterator(); iterator.hasNext();) {
      Path path = iterator.next();
      String filename = path.getFileName().toString(); // The filename here is correct
      ...
    }
    

    So if you are using Java 1.7, you should give a try to new classes into java.nio.file package : it saved my day!

    Hope it helps

提交回复
热议问题