[英]how to read from file that was giving in a command line argument in java?
我想從文件中讀取,其中程序從命令行參數獲取文件名(該文件也是一個 java 文件),然后只打印我想使用java.nio.file.Files
從文件中讀取的文件中的注釋java.nio.file.Files
和java.nio.file.Path
也許。 我應該使用主函數讀取文件名我不知道該怎么做,有什么幫助嗎? 這實際上是我用 Java 編寫的第一個代碼,所以我遇到了很多困難,這是我迄今為止所遇到的:
package firtJavaCode;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.StringTokenizer;
import java.lang.String ;
public class ReadFromFile {
public static void main(String[] args) {
try {
//String filePath = ""; // here is my problem i don't know how to read from a giving file
String line;
BufferedReader br = new BufferedReader(new FileReader(filePath));
int lineNumber = 0;
while ((line = br.readLine()) != null) {
lineNumber++;
if (line.contains("//")) {
StringTokenizer st1 = new StringTokenizer(line, "//");
System.out.println(st1.nextToken());
}
// i still didn't complete the code , just want to figure how to read from file first
}
}catch (Exception e) {
System.out.println(e);
}
}
}
您有在 String[] args 數組中寫入控制台的參數。 為了獲取文件名,我們假設您像這樣執行程序: java example /home/file.txt
。
args[0] == "/home/file.txt"
因此文件路徑已作為字符串保存在args[0]
,因此您不需要代碼中的額外String filepath
。
BufferedReader br = new BufferedReader(new FileReader(args[0]));
所以基本上你在程序名稱之后放入的參數都保存在String args[]
數組中。
我還將實現一種方法來檢查是否只輸入了文件路徑,而不是像這樣的其他一些廢話:
if (args.length() > 0)
{
System.out.println("Error! Too many arguments entered!");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.