There is a method for reading a large text file, but the code does not seem to me correct, and I would like to make it somehow get rid of this if(amountData != -1)... This if as a result of the following problem: when the file reading came to an end, and the last iteration of the loop remained, the buffer size significantly exceeded the number of bytes that were left for reading, and as a result I had at the end of the variable I placed the data that I read from the file a large amount squares (not decrypted characters). I understand that these squares are those null that were not filled in the buffer (the rest of the data in the file was not enough), and in order to get rid of them I began to check how much data I actually read. And it works.
I would like to abandon this backup, and use the tools of the standard API, but I do not know how. Help me please.
private void read() { String path = "/Users/pavel/Desktop/test/target_text.txt"; try (BufferedInputStream in = new BufferedInputStream( new FileInputStream(path))) { byte[] bytes = new byte[1024]; int amountData = in.read(bytes, 0, 1024); while (amountData != -1 && amountData == 1024) { sb.append(new String(bytes, "UTF8")); amountData = in.read(bytes, 0, 1024); } if (amountData != -1) { byte[] residue = new byte[amountData]; System.arraycopy(bytes, 0, residue, 0, residue.length); sb.append(new String(residue, "UTF8")); } System.out.println(sb); } catch (IOException e) { e.printStackTrace(); } }