Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/391.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用java读取新行字符_Java_Line_Newline - Fatal编程技术网

使用java读取新行字符

使用java读取新行字符,java,line,newline,Java,Line,Newline,伙计们,我刚刚在网上看到了这个例子。我想使用它以包含新行的相同格式打印文本文件的内容,但它只打印出第一行。谢谢 import java.util.*; import java.io.*; public class Program { public static void main(String[] args)throws Exception { Scanner scanner = new Scanner(n

伙计们,我刚刚在网上看到了这个例子。我想使用它以包含新行的相同格式打印文本文件的内容,但它只打印出第一行。谢谢

 import java.util.*;
 import java.io.*;

      public class Program
      {
          public static void main(String[] args)throws Exception
          {
          Scanner scanner = new Scanner(new FileReader("B:\\input.txt"));
          String str = scanner.nextLine(); 

          // Convert the above string to a char array.
          char[] arr = str.toCharArray();

          // Display the contents of the char array.
          System.out.println(arr);
          }
      }
nextLine()方法只提供一行,您必须调用它,直到有一个null(~C的EOF)


nextLine()方法只提供一行,您必须调用它直到有一个null(~C的EOF)

试试这个。。要按原样读取整个文件

File f = new File("B:\\input.txt");
FileReader fr = new FileReader(f);
BufferedReader br  = new BufferedReader(fr);

String s = null;

while ((s = br.readLine()) != null) {
    // Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}

br.close();
但如果仍要使用扫描仪,请尝试此…

while ( scan.hasNextLine() ) {
    str = scan.nextLine();
    char[] arr = str.toCharArray();
}

试试这个。。要按原样读取整个文件

File f = new File("B:\\input.txt");
FileReader fr = new FileReader(f);
BufferedReader br  = new BufferedReader(fr);

String s = null;

while ((s = br.readLine()) != null) {
    // Do whatever u want to do with the content of the file,eg print it on console using SysOut...etc
}

br.close();
但如果仍要使用扫描仪,请尝试此…

while ( scan.hasNextLine() ) {
    str = scan.nextLine();
    char[] arr = str.toCharArray();
}

你需要一个循环来逐行阅读。看一看。Scanner类有一个hasNext()方法,因此只要Scanner有另一个令牌要读取,您就可以循环,并在循环中使用nextLine()一次读取一行。您需要一个循环来逐行读取。请查看。Scanner类有一个hasNext()方法,因此只要Scanner有另一个标记要读取,您就可以循环,并在循环中使用nextLine()一次读取一行,但正如问题中所述,我照着原样写了它。因为我已经犯了一些错误,试图纠正无意中犯的错误。请使用
/
而不是
\\
,这样它就可以在每个操作系统上工作,而不是只在Windows上工作。是的……这是一个很好的提示。。我曾经研究过网络路径“\\”,浏览器路径“//”,“文件夹“/”,网页“/”在Linux和Cisco设备上工作。甚至我都想知道它,但因为它是在问题中,我就这样写了。因为我已经犯了一些错误,试图纠正这些非故意的错误。使用
/
而不是
\
,这样它就可以在每个操作系统上工作,而不是只在Windows上工作。是的……这是一个很好的提示。。我研究过一次网络路径“\\”,浏览器路径“//”,“文件夹“/”,网页“/”,“/”在Linux和Cisco设备中工作。。