extract matched line from text file - java

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();

Related

Is there a way for Java Scanner to include '\n' when it is reading lines?

Is there any way for java.util.Scanner to include the newline escape character when reading from a file?
This is my code:
File myFile = new File("file.txt");
Scanner myReader = new Scanner(myFile);
String content = "";
while(myReader.hasNextLine()) {
content += myReader.nextLine();
}
System.out.println(content);
myReader.close();
When it reads from the file, it doesn't include '\n' or any new lines. Does anyone know how to do this?
Thanks
When it reads from the file, it doesn't include '\n' or any new lines.
Does anyone know how to do this?
You can add the new line explicitly as follows:
while(myReader.hasNextLine()) {
content += myReader.nextLine() + "\n";
}
I also recommend you use StringBuilder instead of String for appending in a loop.
StringBuilder content = new StringBuilder();
while (myReader.hasNextLine()) {
content.append(myReader.nextLine()).append(System.lineSeparator());
// or the following
// content.append(myReader.nextLine()).append('\n');
}
Check StringBuilder vs String concatenation in toString() in Java to learn more about it.
If you you just want to read in lines and the line terminator you can do it by changing the behavior of Scanner.next(). If you run the following it will take in the line and the new line terminator as one unit.
\\z is a regex directive that says to include the line terminator.
Scanner scan = new Scanner(System.in);
scan.useDelimiter("\\z");
for (int i = 0; i < 5; i++) {
String line = scan.next();
System.out.println(line + "on next line");
}
To read from a file, try this.
try {
Scanner scan = new Scanner(new File("f:/Datafile.txt"));
scan.useDelimiter("\\z");
while (scan.hasNextLine()) {
String line = scan.next();
System.out.print(line);
}
} catch (FileNotFoundException fe) {
fe.printStackTrace();
}

I read file then write the file and the spaces between text disappear

Im reading from a temp file and writing it to a permanent file but somewhere the string loses all its spaces
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
String b, filename;
b = null;
filename = (textfieldb.getText());
try {
// TODO add your handling code here:
dispose();
Scanner scan;
scan = new Scanner(new File("TempSave.txt"));
StringBuilder sb = new StringBuilder();
while (scan.hasNext()) {
sb.append(scan.next());
}
b = sb.toString();
String c;
c = b;
FileWriter fw = null;
try {
fw = new FileWriter(filename + ".txt");
} catch (IOException ex) {
Logger.getLogger(hiudsjh.class.getName()).log(Level.SEVERE, null, ex);
}
PrintWriter pw = new PrintWriter(fw);
pw.print(c);
pw.close();
System.out.println(c);
} catch (FileNotFoundException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
dispose();
hiudsjh x = new hiudsjh();
x.setVisible(true);
System.out.println(b);
}
theres no error messages just the output should be a file with the spaces remaining
Instead of hasNext() and next() with which you don't get the spaces, use hasNextLine() and nextLine() to read the filr line by line and append after each line a line separator:
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
sb.append(System.lineSeparator());
}
From the Scanner documentation:
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
And from the next methods docu
Finds and returns the next complete token from this scanner. A complete token is preceded and followed by input that matches the delimiter pattern.
In other words, the Scanner splits the input String into sequences without whitespaces. To read the file as a String you could use new String(Files.readAllBytes(Paths.get(filePath)), StandardCharsets.UTF_8); to read the entire file.
This:
while (scan.hasNext()) {
sb.append(scan.next());
}
is what is removing the spaces...next() will return the next complete token from the scanner, this does not include spaces. You will need to append spaces or change the way you read the file...
Instead of scannining each token, you can read your file line by line and append a line separator after each line:
while (scan.hasNextLine()) {
sb.append(scan.nextLine());
sb.append(System.lineSeparator());
}

How to read specific parts of a .txt file in 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

readfile in from text file elements java

I'm trying to read in a .txt file in but when i use debugger it gets stuck on nextline? Is there some logic error that im doing? It's all being stored into an array through multiple objects:
public static File readFileInfo(Scanner kb)throws FileNotFoundException
{
System.out.println("Enter your file name");
String name = "";
kb.nextLine();
name = kb.nextLine();
File file = new File(name);
return file;
}
The scanner I passed into it is:
Scanner fin = null, kb = new Scanner(System.in);
File inf = null;
inf = FileUtil.readFileInfo(kb);
fin = new Scanner(inf);
You're reading from two different "files" here:
System.in, the standard input (or "terminal"), which you're using to ask the user for a filename
the file with the name you get from the user
When you call name = kb.nextLine();, you're asking the parameter (the Scanner built with System.in) for its next line. Generally, that will actually block ("hang") until it receives another line of input (the filename) from the user. If running from a command line, enter your text into that window; if running in an IDE, switch to the Console tab and enter it there.
As quazzieclodo noted above, you probably only need to call readLine once.
After that, you can open up your second Scanner based on the File that readFileInfo returns, and then you're actually reading from a text file as expected.
Assuming that your intention is to use Scanner to read a text file:
File file = new File("data.txt");
try {
Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
System.out.println(line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}

User Input File Console/Command Line - Java

Most examples out there on the web for inputting a file in Java refer to a fixed path:
File file = new File("myfile.txt");
What about a user input file from the console? Let's say I want the user to enter a file:
System.out.println("Enter a file to read: ");
What options do I have (using as little code as possible) to read in a user specified file for processing. Once I have the file, I can convert to string, etc... I'm thinking it has to do with BufferedReader, Scanner, FileInputStream, DataInputStream, etc... I'm just not sure how to use these in conjunction to get the most efficient method.
I am a beginner, so I might well be missing something easy. But I have been messing with this for a while now to no avail.
Thanks in advance.
To have the user enter a file name, there are several possibilities:
As a command line argument.
public static void main(String[] args) {
if (0 < args.length) {
String filename = args[0];
File file = new File(filename);
}
}
By asking the user to type it in:
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a file name: ");
System.out.flush();
String filename = scanner.nextLine();
File file = new File(filename);
Use a java.io.BufferedReader
String readLine = "";
try {
BufferedReader br = new BufferedReader(new FileReader( <the filename> ));
while ((readLine = br.readLine()) != null) {
System.out.println(readLine);
} // end while
} // end try
catch (IOException e) {
System.err.println("Error Happened: " + e);
}
And fill the while loop with your data processing.
Regards,
Stéphane

Categories

Resources