0

i built a program that reads xml files an when i run it in netbeans it works and characters are readable look to the imageopening in netbeans

but when i run it from dist folder its works but when i try to open folder that containing arabic language it show characters like in the image opening from dist folder

this is some of opening code

int option = chooser.showOpenDialog(this);
    if(option == JFileChooser.APPROVE_OPTION){
        if(chooser.getSelectedFile()!=null){
            try {
                reader = new FileReader(chooser.getSelectedFile());
                BufferedReader buff = new BufferedReader(reader); 
                text.read(buff, null);
                opened = chooser.getSelectedFile();
                this.setTitle(chooser.getSelectedFile().getAbsolutePath());
            } catch (IOException ex) {
                JOptionPane.showMessageDialog(null, "الملف غير موجود", "خطأ", JOptionPane.ERROR_MESSAGE);
            }finally{
                if(reader!=null)try {
                    reader.close();
                } catch (IOException ex) {

                }
            }
        }
    }

1 Answers1

1

FileReader is an old utility class that uses the default platform encoding. This will vary from computer to computer and is non-portable.

Path path = chooser.getSelectedFile().toPath();
text.read(Files.newBufferedReader(path, StandardCharsets.UTF_8)); 
//text.read(Files.newBufferedReader(path, Charset.forName("Windows-1256")); 

Assuming the Arabic text is stored as either UTF-8 or Windows-1256.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
  • [`FileReader`](http://docs.oracle.com/javase/8/docs/api/java/io/FileReader.html) is just a convenience class combining `InputStreamReader` and `FileInputStream`. The javadoc says so too. Although using the new `Path` APIs is good, there is no need. As the javadoc says: *The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.* That means `new InputStreamReader(new FileInputStream(chooser.getSelectedFile()), "UTF-8")` works too. – Andreas Jul 16 '17 at 02:31
  • @Andreas the point I wanted to make was that FileReader cannot specify the encoding; is for local files. The convenience class Files is good to know too. The advantage of your InputStreamReader is its clear basic nature, bridge between binary ~Stream and text Reader/Writer. Thanks – Joop Eggen Jul 16 '17 at 16:16