scanner next() only -n 个文件中的字符

scanner next() only -n characters from a file

有没有办法在 java 扫描仪中读取下一个 -n 个字符? 假设我想阅读 16 个字符。我读了一行,从中取出 16 个字符,跳到新行,然后继续阅读同一行。如果需要,读取一个新行并从中取出其他字符。

下面是一个简单的例子,一个字符一个字符地读取文件,并在 16 个字符后追加一个新行

摘自 How to read an input file char by char using a Scanner?

public class FileReader
{
  public static void main(String[] args) throws FileNotFoundException
  {

    StringBuilder stringBuilder = new StringBuilder();
    Scanner scanner = null;
    int count = 0;
    try
    {
      scanner = new Scanner(new BufferedReader(new java.io.FileReader("d:\text.txt")));
      while (scanner.hasNext())
      {
        String str = scanner.next();
        char[] myChar = str.toCharArray();
        for (char c : myChar)
        {
          stringBuilder.append(c);
          count++;
          if (count == 16)
          {
            count = 0;
            stringBuilder.append("\n");
          }
        }
      }
      System.out.println(stringBuilder.toString());
    }
    finally
    {
      if (scanner != null)
      {
        scanner.close();
      }
    }
  }
}