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

时间:2015-05-26 12:14:04

标签: java java.util.scanner

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

1 个答案:

答案 0 :(得分:1)

下面是一个简单的例子,用char读取文件char,并在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();
      }
    }
  }
}