[英]Java read file using Scanner
我可以使用java.io
和java.util.Scanner
讀取文件,但是我不知道如何僅使用java.util.Scanner
讀取文件:
import java.io.*;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
Scanner sc = new Scanner(new File(filePath));
int a, b;
a = sc.nestInt();
b = sc.nextInt();
}
}
有人可以幫忙嗎?
由於Scanner需要一個java.io.File對象,因此我認為不存在不使用任何java.io類就只能使用Scanner進行讀取的方法。
這是使用Scanner類讀取文件的兩種方法-使用默認編碼和顯式編碼。 這是有關如何讀取Java文件的長指南的一部分。
掃描儀-默認編碼
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
try (Scanner scanner = new Scanner(file)) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}
掃描儀–顯式編碼
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class ReadFile_Scanner_NextLine_Encoding {
public static void main(String [] pArgs) throws FileNotFoundException {
String fileName = "c:\\temp\\sample-10KB.txt";
File file = new File(fileName);
//use UTF-8 encoding
try (Scanner scanner = new Scanner(file, "UTF-8")) {
String line;
boolean hasNextLine = false;
while(hasNextLine = scanner.hasNextLine()) {
line = scanner.nextLine();
System.out.println(line);
}
}
}
}
如果您想讀取文件直到最后:
String filePath = "C:\\IdeaProjects\\test\\src\\input.txt";
File file = new File(filePath);
try {
Scanner sc = new Scanner(file);
while (sc.hasNextLine()) {
int i = sc.nextInt();
System.out.println(i);
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
ps如果每行只有Integer,建議您使用Integer.parseInt(sc.readLine());。
而不是sc.nextInt();
如果您看不懂,請給我發送文件
好吧,如果您使用的是Mac, file.java<input.txt
鍵入到終端文件file.java<input.txt
然后輸出到您鍵入以下內容的文件中: file.java>output.txt
output.txt
是不存在的文件,而input.txt
是一個預先存在的文件。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.