Joe*_*hez 17 java methods file project
所以这就是我到目前为止所做的:
public String[] findStudentInfo(String studentNumber) {
Student student = new Student();
Scanner scanner = new Scanner("Student.txt");
// Find the line that contains student Id
// If not found keep on going through the file
// If it finds it stop
// Call parseStudentInfoFromLine get the number of courses
// Create an array (lines) of size of the number of courses plus one
// assign the line that the student Id was found to the first index value of the array
//assign each next line to the following index of the array up to the amount of classes - 1
// return string array
}
Run Code Online (Sandbox Code Playgroud)
我知道如何找到一个文件是否包含我想要找到的字符串,但我不知道如何检索它所在的整行.
这是我第一次发帖所以如果我做错了请告诉我.
Ami*_*ani 48
你可以这样做:
File file = new File("Student.txt");
try {
Scanner scanner = new Scanner(file);
//now read the file line by line...
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if(<some condition is met for the line>) {
System.out.println("ho hum, i found it on line " +lineNum);
}
}
} catch(FileNotFoundException e) {
//handle this
}
Run Code Online (Sandbox Code Playgroud)
MGP*_*GPJ 11
使用Apache Commons IO API https://commons.apache.org/proper/commons-io/我能够使用它来建立这个FileUtils.readFileToString(file).contains(stringToFind)
当你阅读文件时,你是否考虑过逐行阅读?这将允许您检查您的行是否包含您正在读取的文件,然后您可以基于此执行您需要的任何逻辑?
Scanner scanner = new Scanner("Student.txt");
String currentLine;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Perform logic
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用变量来保存行号,也可以使用布尔值来指示是否已传递包含字符串的行:
Scanner scanner = new Scanner("Student.txt");
String currentLine;
int lineNumber = 0;
Boolean passedLine = false;
while((currentLine = scanner.readLine()) != null)
{
if(currentLine.indexOf("Your String"))
{
//Do task
passedLine = true;
}
if(passedLine)
{
//Do other task after passing the line.
}
lineNumber++;
}
Run Code Online (Sandbox Code Playgroud)
这是在文本文件中查找字符串的 java 8 方法:
for (String toFindUrl : urlsToTest) {
streamService(toFindUrl);
}
private void streamService(String item) {
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
stream.filter(lines -> lines.contains(item))
.forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
Run Code Online (Sandbox Code Playgroud)