Read file, one line at a time and run code - java

I have a file with text in this format:
text:text2:text3
text4:text5:text6
text7:text8:text9
Now what I want to do, is to read the first line, separate the words at the ":", and save the 3 strings into different variables. those variables are then used as parameter for a method, before having the program read the next line and doing the same thing over and over again.. So far I've got this:
public static void main(String[] args) {
BufferedReader reader = null;
try {
File file = new File("C://Users//Patrick//Desktop//textfile.txt");
reader = new BufferedReader(new FileReader(file));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Also, I've tried this for separation (although not sure Array is the best option:
String[] strArr = sCurrentLine.split("\\:");

Use String[] parts = line.split(":"); to get an array with text, text2 etc. You can then loop through parts and call the method you want with each item in the list.
Your original split does not work, because : is not a special character in Regex. You only have to use an escape character when the split you are trying to achieve uses a special character.
More information here.

Related

assigning properties to strings in text file

Hopefully my explanation does me some justice. I am pretty new to java. I have a text file that looks like this
Java
The Java Tutorials
http://docs.oracle.com/javase/tutorial/
Python
Tutorialspoint Java tutorials
http://www.tutorialspoint.com/python/
Perl
Tutorialspoint Perl tutorials
http://www.tutorialspoint.com/perl/
I have properties for language name, website description, and website url. Right now, I just want to list the information from the text file exactly how it looks, but I need to assign those properties to them.
The problem I am getting is "index 1 is out of bounds for length 1"
try {
BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"));
while (in.readLine() != null) {
TutorialWebsite tw = new TutorialWebsite();
str = in.readLine();
String[] fields = str.split("\\r?\\n");
tw.setProgramLanguage(fields[0]);
tw.setWebDescription(fields[1]);
tw.setWebURL(fields[2]);
System.out.println(tw);
}
} catch (IOException e) {
e.printStackTrace();
}
I wanted to test something so i removed the new lines and put commas instead and made it str.split(",") which printed it out just fine, but im sure i would get points taken off it i changed the format.
readline returns a "string containing the contents of the line, not including any line-termination characters", so why are you trying to split each line on "\\r?\\n"?
Where is str declared? Why are you reading two lines for each iteration of the loop, and ignoring the first one?
I suggest you start from
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
and work from there.
The first readline gets the language, the second gets the description, and the third gets the url, and then the pattern repeats. There is nothing to stop you using readline three times for each iteration of the while loop.
you can read all the file in a String like this
// try with resources, to make sure BufferedReader is closed safely
try (BufferedReader in = new BufferedReader(new FileReader("Tutorials.txt"))) {
//str will hold all the file contents
StringBuilder str = new StringBuilder();
String line;
while ((line = in.readLine()) != null) {
str.append(line);
str.append("\n");
} catch (IOException e) {
e.printStackTrace();
}
Later you can split the string with
String[] fields = str.toString().split("[\\n\\r]+");
Why not try it like this.
allocate a List to hold the TutorialWebsite instances.
use try with resources to open the file, read the lines, and trim any white space.
put the lines in an array
then iterate over the array, filling in the class instance
the print the list.
The loop ensures the array length is a multiple of nFields, discarding any remainder. So if your total lines are not divisible by nFields you will not read the remainder of the file. You would still have to adjust the setters if additional fields were added.
int nFields = 3;
List<TutorialWebsite> list = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader("tutorials.txt"))) {
String[] lines = in.lines().map(String::trim).toArray(String[]::new);
for (int i = 0; i < (lines.length/nFields)*nFields; i+=nFields) {
TutorialWebsite tw = new TutorialWebsite();
tw.setProgramLanguage(lines[i]);
tw.setWebDescription(lines[i+1]);
tw.setWebURL(lines[i+2]);
list.add(tw);
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
list.forEach(System.out::println);
A improvement would be to use a constructor and pass the strings to that when each instance is created.
And remember the file name as specified is relative to the directory in which the program is run.

Java how to read a file line by line and change the specific part of the line [duplicate]

This question already has answers here:
Modify the content of a file using Java
(6 answers)
Closed 3 years ago.
I am new at java and teacher gave us a project homework. I have to implement read the file line by line, slice the lines at the comma and store the parts at a multidimensional array, change the specific part of the line (I want to change the amount).
The given file:
product1,type,amount
product2,type,amount
product3,type,amount
product4,type,amount
product5,type,amount
I tried this code but I couldn't change the specific part.
BufferedReader reader;
int j=0;
int i=0;
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
j++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
String total_length[][]=new String[j][3];
try {
reader = new BufferedReader(new FileReader("file.txt"));
String line = reader.readLine();
while (line != null) {
line = reader.readLine();
String[] item = line.split(",");
total_length[i][0]=item[0];
total_length[i][1]=item[0];
total_length[i][2]=item[0];
i++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
Thanks a lot!
First, you need to read the file. There are plenty of way to do it, one of them is:
BufferedReader s = new BufferedReader(new FileReader("filename"));
Which allows you to do s.readLine() to read it line by line.
You can use a while loop to read it until the end. Note that readLine will return null if you reach the end of the file.
Then, for each line, you want to split them with the coma. You can use the split method of Strings:
line.split(",");
Putting it all together, and using a try-catch for IOException, you get:
List<String[]> result = new ArrayList<>();
try (BufferedReader s = new BufferedReader(new FileReader("filename"))) {
String line;
while ((line = s.readLine()) != null) {
result.add(line.split(","));
}
} catch (IOException e) {
// Handle IOExceptions here
}
If you really need a two dimensional array at the end, you can do:
String[][] array = new String[0][0];
array = result.toArray(array);
You then have read the file in the format you wanted, you can now modify the data that you parsed.

Create a shortcut/macro that runs a predefined chunk of code?

Sorry if this question has been asked before, but I'm new to coding and I can't find an answer online because I don't know the theory well enough to know how to describe what I'm looking for.
Basically, I want to know if theres a way I can initialize a variable/macro that I can tie to this long try statement, so instead of writing THIS every time I want to read my file
System.out.println("filler");
System.out.println("filler");
try {
FileReader reader = new FileReader("MyFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("filler");
System.out.println("filler");
I can just write something like..
System.out.println("filler");
System.out.println("filler");
Read1
System.out.println("filler");
System.out.println("filler");
As #king_nak suggests, use a method.
public void readFile(String path) {
try {
FileReader reader = new FileReader(path);
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
And then you can do what you wanted:
System.out.println("filler");
readFile("MyFile.txt") // call the method
System.out.println("filler");
In Java, MACROS are called constants instead, and are initialised with the final keyword.
For having a String constant for example:
final String str = "Hello World!";
What you need here, is a good ol' fashioned Java method.
You need to declare it outside your main method, in a class of your choosing. What the following method will do, is that it will read a file and add each line of the file to a list (an ArrayList more specifically).
Each element of the ArrayList is one line of text, read from the file.
Note: This method is quite advanced, since it utilises streams to achieve what was described above. If you use this, then please spend some time to understand it first! Otherwise, I would suggest you don't use this as a beginner. (You can read the documentation for for Reading, Writing and Creating files).
public ArrayList<String> readLines (String filename){
ArrayList<String> lines = null;
// Get lines of text from file as a stream.
try (Stream<String> stream = Files.lines(Paths.get(filename))){
// convert stream to a List-type object
lines = (ArrayList<String>)stream.collect(Collectors.toList());
}
catch (IOException ioe){
System.out.println("Could not read lines of text from the file..");
ioe.printStackTrace();
}
return lines;
}
Then you can use the method like so:
ArrayList<String> lines = null; //Initialise an ArrayList to store lines of text.
System.out.println("filler");
lines = readLines("/path/myFile.txt");
System.out.println(lines.get(0)); //Print the first line of text from list
System.out.println("filler");
lines = readLines("/path/myOtherFile.txt");
for( String str : lines )
System.out.println(str); //Will print every line of text in list
Here is the link for the documentation for java.nio.Files.

How to read the first element/term of a line in Java?

My aim is to read the first element/term of each line from a given input file and then decide what to do (using an if-else construct) depending on what that first element is. I.e. if the first element/word happens to be "the" (as mentioned in the code below), then I have to skip that line and move to the next line.
I have written the following code till now but I am not sure on how to read only the first element of each line of the text file that I am passing as input.
public static void main(String[] args) {
BufferedReader br = null;
try {
String line;
br = new BufferedReader(new FileReader("input.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
StringTokenizer stringTokenizer = new StringTokenizer(line, " ");
while (stringTokenizer.hasMoreTokens()) {
String term = stringTokenizer.nextElement().toString();
if (term.equals("the")) {
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
}
System.out.println("Done!");
}
catch (IOException e)
{
e.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
Below is the simple code that prints the as the output. you can use this and no need to create an extra array or use StringTokenizer.
String s = "The a an the abcdef.";
System.out.println(s.contains(" ") ? s.substring(0, s.indexOf(" ")) : s);
You can turn each term into an array of words via:
while((line = br.readLine()) != null){
System.out.println(line);
String word = line.split("\\s+")[0];
if(word.equals("the")){
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
...
but I am not sure on how to read only the first element of each line of the text file that I am passing as input.
There are a couple of different solutions depending on your exact requirement.
You can read the entire line of data and then use the String.startsWith(...) method to test for the first word. Using this approach you don't tokenize all the data if you just want to skip the rest of the line. Then if you want to continue processing you can use the String.substring(...) method to get the rest of the data from the line.
You can use the Scanner class. The Scanner allows you to tokenize the input as you read the data from the file. So you can read the first word and then determine whether to skip the rest of the data or read the rest of the line.
StringTokenizer is considered as legacy class. It is only there for backward compatibility. Use split() on string to split the single string into array of strings/words.
String[] s = line.readLine().split(" ");
String firstWord = s[0]; // ->First word
So your code can be edited to
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String line;
br = new BufferedReader(new FileReader("input.txt"));
while((line = br.readLine()) != null)
{
System.out.println(line);
String s = line.split(" "); // instead of StringTokenizer
if(s[0].equals("the"))
{
//Code on what to do depending on the first character of each line.
}
StringBuilder sb = new StringBuilder();
System.out.println(sb.toString());
}
System.out.println("Done!");
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
try
{
if (br != null)
br.close();
}
catch(IOException ex)
{
ex.printStackTrace();
}
}
}
Note:
Don't use startsWith(...) to check for the first word because it checks by character-wise instead of word-wise. If you want to check for the word the then the words there,their also returns true which might break your code.
Try to use split() instead of StringTokenizer from now onwards.

Struggling to parse different text files based on their delimiters

Ive been working on this on and off today.
Here is my method, which basically needs to accept a .data (txt) file location, and then go through the contents of that text file and break it up into strings based on the delimiters present. These are the 2 files.
The person file.
Person ID,First Name,Last Name,Street,City
1,Ola,Hansen,Timoteivn,Sandnes
2,Tove,Svendson,Borgvn,Stavanger
3,Kari,Pettersen,Storgt,Stavanger
The order file.
Order ID|Order Number|Person ID
10|2000|1
11|2001|2
12|2002|1
13|2003|10
public static void openFile(String url) {
//initialize array for data to be held
String[][] myStringArray = new String[10][10];
int row = 0;
try {
//open the file
FileInputStream fstream = new FileInputStream(url);
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
//ignores any blank entries
if (!"".equals(strLine)) {
//splits by comma(\\| for order) and places individually into array
String[] splitStr = new String[5];
//splitStr = strLine.split("\\|");
/*
* This is the part that i am struggling with getting to work.
*/
if (strLine.contains("\\|")) {
splitStr = strLine.split("\\|");
} else if (strLine.contains(",")) {
splitStr = strLine.split(",");
}else{
System.out.println("error no delimiter detected");
}
for (int i = 0; i < splitStr.length; i++) {
myStringArray[row][i] = splitStr[i];
System.out.println(myStringArray[row][i]);
}
}
}
//Close the input stream
br.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
}
The person file is correctly read and parsed. But the order file with the "|" delimiter is having none of it. I just get 'null' printouts.
Whats confusing me is that when i just have splitStr = strLine.split("\|"); It works but i need this method to be able to detect the delimiter present and then apply the correct split.
Any help will be much appreciated
Apart from the fact that this should be done using a CSV library, the reason this code is failing is that contains doesnt accept a regular expression. Remove the escape characters so the pipe character can be detected
if (strLine.contains("|")) {

Categories