Environment setup
Sample 1
- Read a file line by line
- Split that line to find a string
- Compare that string with the string users has inputted
- Result
filename.txt[html]
Southern Cross Station^1^3501^Spencer Street^Melbourne
William Street^3^3503^Collins Street^Melbourne
Elizabeth Street^5^3505^Collins Street^Melbourne
[/html]Tram.java
[java]
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.BufferedReader;
import java.io.FileReader;public class Tram {
public static void main(String[] args) {// Print out ‘Enter filename’
System.out.println("Enter filename >> ");
Scanner scanner = new Scanner(System.in);
String fileName = scanner.nextLine();// Print out ‘Enter tram tracker id’
System.out.println("Enter tram tracker id >> ");
String trackerId = scanner.nextLine();// Get folder path
String dir = System.getProperty("user.dir");
String filePath = dir + "\\" + fileName;
System.out.println(filePath);// Check if file exist or not
File file = new File(filePath);
if(!file.exists() || file.isDirectory()) {
// do something
System.out.println("File not found");
} else
{
// Read the file line by line
try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
String line;
Boolean isFound = false;
while ((line = br.readLine()) != null) {
String[] sections = line.split("\\^");
String trackerIdFound = sections[2];
if (trackerId.equals(trackerIdFound)) {// Found trackerId
isFound = true;
System.out.println("Tracker id: " + trackerId);
System.out.println("Stop number: " + sections[1]);
System.out.println("Road: " + sections[3]);
System.out.println("Cross Street: " + sections[0]);
System.out.println("Suburb: " + sections[4]);break;
}
}if (isFound == false) {
System.out.println("That tracker id was not found");
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}[/java]
Leave a Reply