public void writeLine(String path, String text) { File f = new File(path); try { f.createNewFile(); FileOutputStream fos = new FileOutputStream(f); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(text); osw.close(); fos.close(); Log.d(TAG, "writeLine: length" + text.length()); Log.d(TAG, "writeLine: length" + f.length()); Log.d(TAG, "writeLine: string json " + text); } catch (IOException e) { e.printStackTrace(); } } 

line 75 is long and file 95 is long. When reading, extra characters are written (diamonds with a question in the console)

Line read: {"dictionary": {"machine": "car", "milk": "milk", "dog": "dog", "mother": "mam", "bread": "bread"}

  public char[] readLine(String path) { File f = new File(path); BufferedReader br = null; try { FileReader fr = new FileReader(f); Log.d("lab2","Файл открыт: " + path); br = new BufferedReader(fr); } catch (IOException e) { Log.d("lab2","Файл НЕ открыт: " + path); } try{ if(br!=null) { Log.d(TAG, "readLine: file length " + f.length()); char arr[] = new char[(int)f.length()]; br.read(arr); Log.d("lab2","Cтрока прочитана: " + new String(arr)); Log.d("lab2","Length: " + arr.length); br.close(); return arr; } } catch (IOException e) { Log.d("lab2","Cтрока НЕ прочитана: " + path); } return null; } 
  • one
    create a minimal, self-contained and reproducible example. how to do this is described here.stackoverflow.com/help/mcve - Mikhail Vaysman
  • I checked with the regular string (hello world), everything works, but when I insert json such a problem appears. - Sanych Goilo
  • usually when trying to create a minimal, self-sufficient and reproducible example, they very quickly discover the problem. try it - maybe you can do it too. - Mikhail Vaysman
  • f.length() returns the file size in bytes, and you create a character array. Since the file is most likely in utf8, there are fewer letters in it (Russians occupy 2 bytes), and you get a string with zero characters at the end. - zRrr
  • @SanychGoilo Do you need to read one line or the entire file? - Evgeniy

1 answer 1

Try using the following method to read:

 public char[] readLine(String path) { File f = new File(path); BufferedReader br = null; try { FileReader fr = new FileReader(f); Log.d("lab2","Файл открыт: " + path); br = new BufferedReader(fr); } catch (IOException e) { Log.d("lab2","Файл НЕ открыт: " + path); } try{ if(br!=null) { Log.d(TAG, "readLine: file length " + f.length()); StringBuilder text = new StringBuilder(); String line; while((line = br.readLine()) != null) { Log.d("lab2","Cтрока прочитана: " + line); Log.d("lab2","Length: " + line.length()); text.append(line); } br.close(); return text.toString().toCharArray(); } } catch (IOException e) { Log.d("lab2","Cтрока НЕ прочитана: " + path); } return null; }