Reading Strings from text files in java - java

im studying for my programming final exam. I have to write a program which opens a file which is stored in the string fileName and look in the file for a String called personName and this should print the first string after personName then the program should terminate after printing it,
if the argument personName is not in the file then it should print "this name doen't exsit" then if an IOException occurs it should then print "there is an IO Error" and the program should exsit using system.exit(0)
the program should use the file info.txt and each line should contain two strings
first string name and second age.
everything must be in one method
data.txt contains
Max 60.0
joe 19.0
ali 20.0
my code for this so far is :
public class Files{
public void InfoReader(String fileName, String personName)
{
try{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("C://rest//data.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//Read File Line By Line
while ((fileName = br.readLine()) != null) {
// Print the content on the console
(new Files()).infoReader("info.txt","Joe"); //this prints the age
}
//Close the input stream
in.close();
}
catch (IOException e)
{//Catch exception if any
System.out.println(" there is an IO Error");
System.exit(0);
}
}
catch (Exception e)
{//Catch exception if any
System.out.println("that name doesn't exists");
}
}
}
infoReader(info.txt,Joe); should print 19.0
But I am getting a java.lang.StackOverflowError
any help would be much appreciated!!
Thanks in advance!

This is what I think you are trying to do. And if doesn't, at least can work as an example. Just as amit mentions, your current error is because of the recursive call, which I think is not necessary.
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class Files {
public void InfoReader(String fileName, String personName) {
try {
// Open the file that is the first command line parameter
FileInputStream fstream = new FileInputStream(fileName);
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line = null;
//Loop until there are no more lines in the file
while((line = br.readLine()) != null) {
//Split the line to get 'personaName' and 'age'.
String[] lineParts = line.split(" ");
//Compare this line personName with the one provided
if(lineParts[0].equals(personName)) {
//Print age
System.out.println(lineParts[1]);
br.close();
System.exit(0);
}
}
br.close();
//If we got here, it means that personName was not found in the file.
System.out.println("that name doesn't exists");
} catch (IOException e) {
System.out.println(" there is an IO Error");
}
}
}

If you use the Scanner class, it would make your life so much easier.
Scanner fileScanner = new Scanner (new File(fileName));
while(fileScanner.hasNextLine()
{
String line = fileScanner.nextLine();
Scanner lineScanner = new Scanner(line);
String name = lineScanner.next(); // gets the name
double age = Double.parseDouble(lineScanner.next()); // gets the age
// That's all really! Now do the rest!
}

Use commons-io and dont forget the encoding!
List<String> lines = FileUtils.readLines(file, encoding)

Related

Regular Expressions to Display Messages from a Text Log File

I'm trying to figure out how to use regular expressions to condense and sort the information I'm getting from this code. Here's the code and I'll explain as I go:
import java.io.*;
import java.util.*;
public class baseline
{
// Class level variables
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) throws IOException,
FileNotFoundException { // Start of main
// Variables
String filename;
// Connecting to the output file with a buffer
PrintWriter outFile = new PrintWriter(
new BufferedWriter(
new FileWriter("chatOutput.log")));
// Get the input file
System.out.print("Please enter full name of the file: ");
filename = sc.next();
// Assign the name of the input file to a file object
File log = new File(filename);
String textLine = null; // Null
String outLine = ""; // Null
BufferedWriter bw = null;
try
{
// assigns the input file to a filereader object
BufferedReader infile = new BufferedReader(new FileReader(log));
sc = new Scanner(log);
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
System.out.println(line);
} // End of while
try
{
// Read data from the input file
while((textLine = infile.readLine()) != null)
{
// Print to output file
outLine = textLine;
sc = new Scanner (outLine);
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK"))
outFile.printf("%s\n",outLine);
}// end of while
} // end of while
} // end of try
finally // This gets executed even when an exception is thrown
{
infile.close();
outFile.close();
} // End of finally
} // End of try
catch (FileNotFoundException nf) // Goes with first try
{
System.out.println("The file \""+log+"\" was not found");
} // End of catch
catch (IOException ioex) // Goes with second try
{
System.out.println("Error reading the file");
} // End of catch
} // end of main
} // end of class
So I'm reading an input file, getting only the lines that display "LANTALK", and printing them out to another file. And here is a sample of what the output looks like so far:
14:29:39.731 [D] [T:000FEC] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>922</MBXID><MBXTO>5608</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>It is mailing today right?
</MSGTEXT>
14:41:33.703 [D] [T:000FF4] [F:LANTALK2C] <CMD>LANMSG</CMD>
<MBXID>929</MBXID><MBXTO>5601</MBXTO><SUBTEXT>LanTalk</SUBTEXT><MOBILEADDR>
</MOBILEADDR><LAP>0</LAP><SMS>0</SMS><MSGTEXT>Either today or tomorrow -
still waiting to hear. </MSGTEXT>
And what I need is to get all of the characters between <MSGTEXT> and </MSGTEXT> to be able to display the message cleanly. How should I write this into the code to repeat with every "LANTALK" line and still write out correctly? Thanks!
Try it with Jsoup.
Example:
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
....
while(sc.hasNext())
{
String line=sc.nextLine();
if(line.contains("LANTALK")){
Document doc = Jsoup.parse(line);
Element msg = doc.select("MSGTEXT").first();
System.out.println(msg.text());
}
System.out.println(line);
} // End of while
.....
You can find MSGTEXT using a regex:
<MSGTEXT>(.*?)</MSGTEXT>
However, some of the messages contain newlines, which makes this a bit more difficult.
One way to get past this is to read the entire file into a String, and then look for matches.
try {
String text = new String(Files.readAllBytes(Paths.get(log)));
Matcher m = Pattern.compile("<MSGTEXT>(.*?)</MSGTEXT>", Pattern.DOTALL).matcher(text);
while (m.find()) {
System.out.println("Message: " + m.group(1));
}
} catch (IOException e) {
//Handle exception
}
Console output:
Message: It is mailing today right?
Message: Either today or tomorrow -
still waiting to hear.
Keep in mind that if you are dealing with large log files this approach could use a lot of memory.
Also note that parsing XML with regex is generally considered a bad idea; it works fine for now, but if you plan on doing anything more complicated you should use an XML parser as others have suggested.

Deleting a specific line from a delimited text file by using user input. (Java)

This is my current code:
import java.util.*;
import java.io.*;
public class Adding_Deleting_Car extends Admin_Menu {
public void delCar() throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(successful);
}
}
I would like to delete a certain line of text from a file based on user input. For instance, this is my text file:
AB234KXAZ;Honda;Accord;1999;10000;3000;G
AB234KL34;Honda;Civic;2009;15000;4000;R
CD555SA72;Toyota;Camry;2010;11000;7000;S
FF2HHKL94;BMW;535i;2011;12000;9000;W
XX55JKA31;Ford;F150;2015;50000;5000;B
I would like the user to input the String of their choice, this will will be the first field in the column (eg. XX55JKA31), and then have that line of text deleted from the file. I've found some code online, but I've been unable to use it successfully.
My current code seems to just rewrite everything in the temporary text file, but doesn't delete it.
You are using File.renameTo, which is documented here:
https://docs.oracle.com/javase/8/docs/api/java/io/File.html#renameTo-java.io.File-
According to the documentation, it may fail if the file already exists, and you should use Files.move instead.
Here is the equivalent code with Files.move:
boolean successful;
try {
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
successful = true;
} catch(IOException e) {
successful = false;
}
Note:
Your code which searches for the VIN is also wrong. See Jure Kolenko's answer for one possible solution to that issue.
Moving forward, you should consider using an actual database to store and manipulate this type of information.
Your error lies in the
if(trimmedLine.equals(lineToRemove)) continue;
It compares the whole line to the VIN you want to remove instead of just the first part. Change that into
if(trimmedLine.startsWith(lineToRemove)) continue;
and it works. If you want to compare to a different column use String::contains instead. Also like Patrick Parker said, using Files.move instead of File::renameTo fixes the renaming problem.
Full fixed code:
import java.util.*;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
public class Adding_Deleting_Car{
public static void main(String... args) throws IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("inventory.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the VIN of the car you wish to delete/update: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
System.out.println(trimmedLine);
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
Note that I changed the class definition not to inherit and the method definition to main(String... args), so I could compile on my system.

How to read a specific word in text file and use a condition statement to do something

I'm new to coding in java. Can anyone help me with my codes? I'm currently making a program where you input a string in a jTextArea, and if the input word(s) matches the one in the text file then it will then do something.
For example: I input the word 'Hey' then it will print something like "Hello" when the input word matches from the text file.
I hope you understand what I mean.
Here's my code:
String line;
String yo;
yo = jTextArea2.getText();
try (
InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);
)
{
while ((line = br.readLine()) != null) {
if (yo.equalsIgnoreCase(line)) {
System.out.print("Hello");
}
}
} catch (IOException ex) {
Logger.getLogger(ArfArf.class.getName()).log(Level.SEVERE, null, ex);
}
You can not use equals for line because a line contain many words. You have to modify it to search the index of the word in a line.
try (InputStream fis = new FileInputStream("readme.txt");
InputStreamReader isr = new InputStreamReader(fis, Charset.forName("UTF-8"));
BufferedReader br = new BufferedReader(isr);) {
while ((line = br.readLine()) != null) {
line = line.toLowerCase();
yo = yo.toLowerCase();
if (line.indexOf(yo) != -1) {
System.out.print("Hello");
}
line = br.readLine();
}
} catch (IOException ex) {
}
since you are new in java , I would suggest you to take some time to study java 8 which enable to write more clean codes. below is the solution write in java 8, hope can give a kind of help
String yo = jTextArea2.getText();
//read file into stream,
try (java.util.stream.Stream<String> stream = Files.lines(Paths.get("readme.txt"))) {
List<String> matchLines = stream.filter((line) -> line.indexOf(yo) > -1).collect(Collectors.toList()); // find all the lines contain the text
matchLines.forEach(System.out::println); // print out all the lines contain yo
} catch (IOException e) {
e.printStackTrace();
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class WordFinder {
public static void main(String[] args) throws FileNotFoundException {
String yo = "some word";
Scanner scanner = new Scanner(new File("input.txt")); // path to file
while (scanner.hasNextLine()) {
if (scanner.nextLine().contains(yo)) { // check if line has your finding word
System.out.println("Hello");
}
}
}
}

get Data from text file in java [duplicate]

How do you read and display data from .txt files?
BufferedReader in = new BufferedReader(new FileReader("<Filename>"));
Then, you can use in.readLine(); to read a single line at a time. To read until the end, write a while loop as such:
String line;
while((line = in.readLine()) != null)
{
System.out.println(line);
}
in.close();
If your file is strictly text, I prefer to use the java.util.Scanner class.
You can create a Scanner out of a file by:
Scanner fileIn = new Scanner(new File(thePathToYourFile));
Then, you can read text from the file using the methods:
fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file
And, you can check if there is any more text left with:
fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file
Once you have read the text, and saved it into a String, you can print the string to the command line with:
System.out.print(aString);
System.out.println(aString);
The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.
In general:
Create a FileInputStream for the file.
Create an InputStreamReader wrapping the input stream, specifying the correct encoding
Optionally create a BufferedReader around the InputStreamReader, which makes it simpler to read a line at a time.
Read until there's no more data (e.g. readLine returns null)
Display data as you go or buffer it up for later.
If you need more help than that, please be more specific in your question.
I love this piece of code, use it to load a file into one String:
File file = new File("/my/location");
String contents = new Scanner(file).useDelimiter("\\Z").next();
Below is the code that you may try to read a file and display in java using scanner class. Code will read the file name from user and print the data(Notepad VIM files).
import java.io.*;
import java.util.Scanner;
import java.io.*;
public class TestRead
{
public static void main(String[] input)
{
String fname;
Scanner scan = new Scanner(System.in);
/* enter filename with extension to open and read its content */
System.out.print("Enter File Name to Open (with extension like file.txt) : ");
fname = scan.nextLine();
/* this will reference only one line at a time */
String line = null;
try
{
/* FileReader reads text files in the default encoding */
FileReader fileReader = new FileReader(fname);
/* always wrap the FileReader in BufferedReader */
BufferedReader bufferedReader = new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null)
{
System.out.println(line);
}
/* always close the file after use */
bufferedReader.close();
}
catch(IOException ex)
{
System.out.println("Error reading file named '" + fname + "'");
}
}
}
If you want to take some shortcuts you can use Apache Commons IO:
import org.apache.commons.io.FileUtils;
String data = FileUtils.readFileToString(new File("..."), "UTF-8");
System.out.println(data);
:-)
public class PassdataintoFile {
public static void main(String[] args) throws IOException {
try {
PrintWriter pw = new PrintWriter("C:/new/hello.txt", "UTF-8");
PrintWriter pw1 = new PrintWriter("C:/new/hello.txt");
pw1.println("Hi chinni");
pw1.print("your succesfully entered text into file");
pw1.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new FileReader("C:/new/hello.txt"));
String line;
while((line = br.readLine())!= null)
{
System.out.println(line);
}
br.close();
}
}
In Java 8, you can read a whole file, simply with:
public String read(String file) throws IOException {
return new String(Files.readAllBytes(Paths.get(file)));
}
or if its a Resource:
public String read(String file) throws IOException {
URL url = Resources.getResource(file);
return Resources.toString(url, Charsets.UTF_8);
}
You most likely will want to use the FileInputStream class:
int character;
StringBuffer buffer = new StringBuffer("");
FileInputStream inputStream = new FileInputStream(new File("/home/jessy/file.txt"));
while( (character = inputStream.read()) != -1)
buffer.append((char) character);
inputStream.close();
System.out.println(buffer);
You will also want to catch some of the exceptions thrown by the read() method and FileInputStream constructor, but those are implementation details specific to your project.

adding objects to java queues from a data file

I am trying to add objects to a queue from a data file which is made up of text which is made up of a person's first name and their 6 quiz grades (ie: Jimmy,100,100,100,100,100,100). I am accessing the data file using the FileReader and using BufferReader to read each line of my data file and then tokenize each line using the "," deliminator to divide the names and quiz grades up. Based on what I think my professor is asking for is to create a queue object for each student. The assignment says,
Read the contents of the text file one line at a time using a loop. In this loop, invoke the processInputData method for each line read. This method returns the corresponding Student object. Add this student object to the studentQueue.
If someone could point me the right direction that would be great! Here is my code so far:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
// Create an empty queue of student objects
LinkedList<Student> studentQueue;
studentQueue = new LinkedList<Student>();
// Create an empty map of Student objects
HashMap<String, Student> studentMap = new HashMap<String, Student>();
System.out.printf("Initial size = %d\n", studentMap.size());
// Open and read text file
String inputFileName = "data.txt";
FileReader fileReader = null;
// Create the FileReader object
try {
fileReader = new FileReader(inputFileName);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// BufferReader to read text file
BufferedReader reader = new BufferedReader(fileReader);
String input;
// Read one line at a time until end of file
try {
input = reader.readLine();
while (input != null) {
processInputData(input);
input = reader.readLine();
}
}
catch (IOException e) {
e.printStackTrace();
}
// Close the input
try {
fileReader.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
// Tokenize the data using the "," as a delimiter
private static void processInputData(String data) {
StringTokenizer st = new StringTokenizer(data, ",");
String name = st.nextToken();
String homework1 = st.nextToken();
String homework2 = st.nextToken();
String homework3 = st.nextToken();
String homework4 = st.nextToken();
String homework5 = st.nextToken();
String homework6 = st.nextToken();
// Using the set methods to correspond to the Student object
Student currentStudent = new Student(name);
currentStudent.setHomework1(Integer.parseInt(homework1));
currentStudent.setHomework2(Integer.parseInt(homework2));
currentStudent.setHomework3(Integer.parseInt(homework3));
currentStudent.setHomework4(Integer.parseInt(homework4));
currentStudent.setHomework5(Integer.parseInt(homework5));
currentStudent.setHomework6(Integer.parseInt(homework6));
System.out.println("Input File Processing...");
System.out.println(currentStudent);
}
}
One possible solution to your problem is returning the student in processInputData(..)
private static Student processInputData(String data) {
// the same code
return currentStudent;
}
And in while loop
while (input != null) {
studentQueue.add(processInputData(input));
input = reader.readLine();
}
Also try to manage better your try-catch blocks, cause if your fileReader throws exception then the code will continue running and throw probably a nullPointerException that you don't handle.
try{
fileReader = new FileReader(inputFileName);
BufferedReader reader = new BufferedReader(fileReader);
}catch(IOException ex){
//handle exception;
}finally{
// close resources
}

Categories