Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StringBuilder encoding in Java

I have a method which loads file from sdcard (Android) and then reads it with StringBuilder. The text which im reading is written with my native language characters such as ą ś ć ź ż... StringBuilder (or FileInputStream) can't read them properly unfortunately. How I can set proper encoding ?

here is the code :

File file = new File(filePath);
            FileInputStream fis = null;
            StringBuilder builder = new StringBuilder();

            try {
                fis = new FileInputStream(file);
                int content;
                while ((content = fis.read()) != -1) {
                    builder.append((char) content);
                }

            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (fis != null)
                        fis.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
            System.out.println("File Contents = " + builder.toString());
            contactService.updateContacts(builder.toString());
like image 303
filipp.kowalski Avatar asked Nov 19 '25 13:11

filipp.kowalski


1 Answers

for example you could try an InputStreamReader combinded with a BufferedReader, that should do the trick:

InputStreamReader inputStreamReader = new InputStreamReader((InputStream)fis, "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
    sb.append(line);
}                   

So long, Tom

like image 108
Tom Avatar answered Nov 21 '25 08:11

Tom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!