How to read specific parts of a .txt file in JAVA - java

I have been trying to figure out how to read from a .txt file. I know how to read a whole file, but I am having difficulties reading between two specific points in a file.
I am also trying to use the scanner class and this is what I have so far:
public void readFiles(String fileString)throws FileNotFoundException{
file = new File(fileString);
Scanner scanner = null;
line="";
//access file
try {
scanner = new Scanner(file);
}
catch (FileNotFoundException e) {
System.out.println("File not found.");
}
// if more lines in file, go to next line
while (scanner.hasNext())
{
line = scanner.next();
if (scanner.equals("BGSTART")) //tag in the txt to locate position
{
line = scanner.nextLine();
System.out.println(line);
lb1.append(line); //attaches to a JTextArea.
window2.add(lb1);//adds to JPanel
}
}
.txt file looks something like this:
BGSTART
//content
BGEND
Nothing is posted onto the panel when I run the program.
I am trying to read it between those two points.I don't have a lot of experience in reading from txt file.
Any suggestions?
Thank You.

Assuming that BGSTART and BGEND are on seperate lines, as per #SubOptimal's question, you would need to do this:
boolean tokenFound = false;
while (scanner.hasNextLine())
{
line = scanner.nextLine();
//line, not scanner.
if (line.equals("BGSTART")) //tag in the txt to locate position
{
tokenFound = true;
}
else if (line.equals("BGEND"))
{
tokenFound = false;
}
if(tokenFound)
{
System.out.println(line);
lb1.append(line); //attaches to a JTextArea.
window2.add(lb1);//adds to JPanel
}
}
Some improvements:
try {
Scanner scanner = new Scanner(new FileInputStream(file));
//Moved the rest of the code within the try block.
//As it was before, if there where any problems loading the file, you would have gotten an error message (File not found)
//as per your catch block but you would then have gotten an unhandled null pointer exception when you would have tried to
//execute this bit: scanner.hasNextLine()
boolean tokenFound = false;
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
//line, not scanner.
if (line.equals("BGSTART")) //tag in the txt to locate position
{
tokenFound = true;
} else if (line.equals("BGEND")) {
tokenFound = false;
}
if ((tokenFound) && (!line.equals("BGSTART"))) {
System.out.println(line);
//I am not sure what is happening here.
//lb1.append(line); //attaches to a JTextArea.
//window2.add(lb1);//adds to JPanel
}
}
} catch (Exception e) {
System.out.println("File not found.");
}
File content:
do not show line one
do not show line two
BGSTART
this is a line
this is another line
this is a third line
BGEND
do not show line three
do not show line four

Why don't you use substring? once you have located your BGSTART and BGEND you can capture the string between it somewhere in the lines of the below code:
StringBuilder sb= new StringBuilder();
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
sb.append(line);
}
String capturedString = sampleString.substring(sb.toString().indexOf("BGSTART"),
sb.toString().indexOf("BGEND"));
hope this helps

Almost good, but you are doing:
if (scanner.equals("BGSTART")) //tag in the txt to locate position
You should look for file content in line variable not scanner.
So try this:
if (line.equals("BGSTART")) //tag in the txt to locate position

Related

How do I read multiple lines and end before a certain string using Scanner in Java?

I'm trying to read multiple lines from a text file before reaching a certain string, "***", which I would then like to print out. How do I do this?
Code:
public void loadRandomClass(String filename) {
try {
Scanner scan = new Scanner(new File(filename));
while((scan.hasNextLine()) && !(scan.nextLine().equals("***"))) {
}
scan.close();
} catch (FileNotFoundException e) {
System.out.println("Something went wrong");
e.printStackTrace();
}
}
I have tried some stuff, but it keeps skipping every 2nd line, starting from the 1st and it doesn't stop before "***".
The problem is that scan.nextLine() reads the line and deletes it from the buffer i suppose. Try this:
while(scan.hasNextLine()) {
String next = scan.nextLine();
if(next.contains("***") break;
System.out.println(next);
}

Read a single line from text file & not the entire file (using buffered reader)

I am trying to write a piece of code that reads a single line of text from a text file in java using a buffered reader. For example, the code would output the single line from the text file and then you would type what it says and then it would output the next line and so on.
My code so far:
public class JavaApplication6 {
public static String scannedrap;
public static String scannedrapper;
public static void main(String[] args) throws FileNotFoundException, IOException {
File Tunes;
Tunes = new File("E:\\NEA/90sTunes.txt");
System.out.println("Ready? Y/N");
Scanner SnD;
SnD = new Scanner(System.in);
String QnA = SnD.nextLine();
if (QnA.equals("y") || QnA.equals("Y")) {
System.out.println("ok, starting game...\n");
try {
File f = new File("E:\\NEA/90sTunes.txt");
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = "";
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
}
}
}
}
It outputs:
Ready? Y/N
y
ok, starting game...
(and then the whole text file)
But I wish to achieve something like this:
Ready? Y/N
y
ok, starting game...
(first line of file outputted)
please enter (the line outputted)
& then repeat this, going through every line in the text file until it reaches the end of the text file (where it would output something like "game complete")...
This would read the first line ".get(0)".
String line0 = Files.readAllLines(Paths.get("enter_file_name.txt")).get(0);
This block of code reads the whole file line by line, without stopping to ask for user input:
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
Consider adding a statement to the loop body that seeks some input from the user, like you did above when asking if they were ready ( you only need to add one line of code to the loop, like the line that assigns a value to QnA )

Scanner only searching first line of .txt file

I'm in a beginning programming class, and seem to be having a major issue with searching a text file. What my code should do, based on the assignment:
Accept input, in this case a name and place that input into a .txt file
Allow the user to search for a name, or part of a name, and return all lines with matching text.
I have the input portion of the assignment complete, and am on the verge on completing the retrieval portion, but my code only searches the first line of the .txt file. I am able to print out all lines of the .txt file, and if I search for the name in Line 1 of the .txt file, it will print the line correctly. My issue comes when I am searching for a name that is not on Line 1. Below is my code:
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
if (choice == 2 && retrieve.equalsIgnoreCase("YES") || retrieve.equalsIgnoreCase("Y"))
{
while (retrieve2.equalsIgnoreCase("YES") || retrieve2.equalsIgnoreCase("Y"))
{
FileReader reader = new FileReader("Name_Index.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = bufferedReader.readLine();
System.out.println ("Enter a string of characters in which to search by or enter \"all names\" f$
search_term = gatherInput();
System.out.println("Search results include: ");
ArrayList<String> list = new ArrayList<String>();
Scanner inFile = new Scanner (new File("Name_Index.txt"));
inFile.useDelimiter(",");
while (inFile.hasNextLine())
{
list.add(inFile.nextLine());
}
Collections.sort(list);
if (search_term.equalsIgnoreCase("all names"))
{
for (String temp : list)
{
System.out.println(temp);
}
}
else if (line.toLowerCase().contains(search_term.toLowerCase()))
{
System.out.println(line);
bufferedReader.close();
}
System.out.println("End!");
System.out.println ("Would you like to retrieve names from your index? (YES/NO)");
try
{
retrieve2=input.readLine();
}
catch (IOException E)
{
System.out.println(E);
}
}
System.out.println("Thank you, come again!");
}
}
public static String gatherInput()
{
Scanner scan = new Scanner(System.in);
String user_input = scan.nextLine();
return user_input;
}
}
I have tried expanding the while (inFile.hasNextLine()) loop to include the second "if" statement, however that creates an issue for the "all names" search - it returns the entire list multiple times (however many lines are in the file). I have even tried creating another while (inFile.hasNextLine()) loop within the second "if" statement, and there is no difference in outcome.
I'm so frustrated at this point, because I've been working on this code for over a week, and have reviewed all of my notes and lecture recordings for this assignment with no help. Any insight would be much appreciated.
You are reading only 1 line of the file
String line = bufferedReader.readLine();
Why don't you read all lines and store them in a List;
List<String> lines = new ArrayList<>();
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
bufferedReader.close();
Then to print all lines containing a substring ignorecase:
lines.stream().filter(l -> l.toLowerCase().contains(search_term.toLowerCase))
.forEach(s -> System.out.println(s));
You need to loop the readLine()
For example:
File f = new File(ruta);
if(!f.exists()) //Error
else {
#SuppressWarnings("resource")
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
//line = the next line
}
}

Detect first line of text file separately?

I am designing a program that will load a text file into different media file classes (Media > Audio > mp3, Media > Video > Avi, etc).
Now the first line of my text file is how many files there are in total, as in
3
exmaple.mp3,fawg,gseges
test.gif,wfwa,rgeg
ayylmao.avi,awf,gesg
Now that is what is in my text file, I want to first get the first line separately, then loop through the rest of the files.
Now I understand I can simply count how many files are in by using an int that grows as I loop but I want it clear in the file aswell, and I'm not sure how to go about this.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line = reader.readLine();
while(line != null)
{
//Get the first line of the text file seperatly? (Then maybe remove it? idk)
//Split string, create a temp media file and add it to a list for the rest of the lines
}
//String[] split = s.next().split(",");
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
I hope my question is clear, if it TL;DR I want to get the first line of a text file separately, then the rest Id like to loop through.
I wouldn't advice using a for-loop here, since the file might contain additional lines (e.g. comments or blank lines) to make it more human-readable. By examining the content of each line, you can make your processing more robust against this sort of thing.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
String line = reader.readLine(); // <-- Get the first line. You could consider reader as a queue (sort-of), where readLine() dequeues the first element in the reader queue.
int numberOfItems = Integer.valueOf(line); // <-- Create an int of that line.
// Do the rest:
while((line = reader.readLine()) != null) // <-- Each call to reader.readLine() will get the next line in the buffer, so the first time around this will give you the second line, etc. until there are no lines left to read.
{
// You will not get the header here, only the rest.
if(!line.isEmpty() || line.startsWith("#") {
// If the line is not empty and doesn't start with a comment character (I chose # here).
String[] split = line.split(",");
String fileName = split[0];
// etc...
}
}
} catch (Exception ex) { System.out.println(ex.getMessage()); }
return null;
}
You don't need while loop to read up to end of file. Read first line and convert it to int than loop through.
static public Media[] importMedia(String fileName)
{
try {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
// Get and process first line:
int lineNo=Integer.parseInt(reader.readLine());
// Now read upto lineNo
for(int i=0; i < lineNo; i++){
//Do what you need with other lines.
String[] values = reader.readLine().split(",");
}
} catch (Exception e) {
//Your exception handling goes here
}
}

extract matched line from text file

a:b:c:d:e
bb:cc:dd:ee:ff
ccc:ddd:eee:fff:ggg
I have a textfile content above. I am trying to compare my user input with the text file. For example
cc:dd
When it is found, I need to retrieve the entire line. How can I retrieve the line which my user input? I have tried using while(scanner.hasNext()) but I could not get my desire outcome.
With standard Java libraries:
File file = new File("file.txt");
String word = "abc";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
//handle this
}
//now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.contains(word)) {
System.out.println(line);
}
}
scanner.close();

Categories

Resources