Java打印文本文件输出并检查第一个字符
我认为我的代码中注释掉的部分是有效的。我的问题是当我打印出字符串“s”时,我只得到文本文件的最后一行Java打印文本文件输出并检查第一个字符,java,java.util.scanner,string-parsing,Java,Java.util.scanner,String Parsing,我认为我的代码中注释掉的部分是有效的。我的问题是当我打印出字符串“s”时,我只得到文本文件的最后一行 import java.io.File; import java.util.Scanner; public class mainCode { public static void main(String[] args)throws Exception { // We need to provide file path as the paramete
import java.io.File;
import java.util.Scanner;
public class mainCode {
public static void main(String[] args)throws Exception
{
// We need to provide file path as the parameter:
// double backquote is to avoid compiler interpret words
// like \test as \t (ie. as a escape sequence)
File file = new File("F:\\Java Workspaces\\Workspace\\Files\\file.txt");
Scanner sc = new Scanner(file);
String s = new String("");
while (sc.hasNextLine())
s = sc.nextLine();
System.out.println(s);
// if (s.substring(0,1).equals("p") || s.substring(0,1).equals("a") ){
// System.out.println(s);
// }
// else{
// System.out.println("Error File Format Incorrect");
// }
}
}
输出仅为“a192”前面的行是“a191”和“a190”缩进使它看起来像您的
,而
执行多个语句,但它不是。使用大括号将要作为块执行的语句括起来
while (sc.hasNextLine())
s = sc.nextLine();
System.out.println(s); // proper indentation
可能是你想要的:
while( sc.hasNextLine() ) {
s = sc.nextLine();
System.out.println( s );
}
(我必须把它放到我的IDE中才能找到它。我的IDE将第二行标记为“令人困惑的缩进”。好的IDE可以做到这一点。)您是否尝试打印出
的结果。子字符串(0,10)
?它可能会显示您的文件中有一些您不期望的内容。(仅仅因为这行打印的是“a”,并不意味着这实际上是第一个字符。存在不可见的字符。)@markspace代码的输出只打印最后一行,即使没有我注释掉的内容,while循环中唯一的行是s=sc.nextLine();和系统输出打印项次;我还实现了类似的代码在C++中没有任何问题。也可以在不使用变量“s”的情况下进行打印,只输出System.out.println(sc.nextLine());正确地打印每一行。天哪,你是对的,我不知道我怎么没有注意到!非常感谢。