I have used two file reading classes , scanner and bufferedReader. While reading the code you have to avoid the part of one of them. I have written them together just for ease to understand. Now question is why i am getting errors while using buffered reader instead of scanner class for this code. Scanner works fine with this code. I am getting exception error at parseRecord method. In this code i am trying to parse a csv, i have several classes which are using its output but i am stuck here and wonder why bufferedReader is not working the same way as scanner.
public List<? extends ReportRecord> load() throws Exception {
List<SportPopularityReportRecord> records=new ArrayList<SportPopularityReportRecord>();
// first way using buffered reader, please ignore the scanner part below.
BufferedReader br;
try {
br= new BufferedReader(new FileReader(filePath.toString()));
String line=br.readLine();
if ((line = br.readLine()) != null)
{
parseHeader(line);
}
while(line != null)
{
line= br.readLine();
records.add(parseRecord(line));
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
br.close();
// fis.close();
}
}
// Second way using scanner class, please ignore the buffered reader part above.
String s;
Scanner sc=new Scanner(filePath.toFile());
//getting header
if(sc.hasNextLine()){
s=sc.nextLine();
parseHeader(s);
}
//getting recored
while(sc.hasNextLine()){
s=sc.nextLine();
records.add(parseRecord(s));
}
//sort the record
Collections.sort(records, new SportPopularityReportRecordComparator());
recordList=records;
//return record List
return recordList;
}
public SportPopularityReportRecord parseRecord(String strRecord) {
String [] s=strRecord.split(",");
SportPopularityReportRecord r=new SportPopularityReportRecord();
r.setSport(s[0]);
r.setRank(Integer.parseInt(s[1]));
return r;
}
try this it will work.
String line=br.readLine();
if (line != null)
{
parseHeader(line);
}
You are reading things two times.
Related
Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
So I have this method here that should return the amount of lines in a csv file. Pretty simple right? Thing is instead of returning the amount of lines in the csv file(in this case 15) it returns 66. I honestly have know Idea why this would happen. I checked the csv file and verified that it is indeed 15 lines long with no empty lines. Also does anyone know why my Jpanes wont display without those three lines commented lines, my ide says the variables aren't in use anywhere.
public static int getLineCount(){
int line=0;
try {
Scanner inputStream = new Scanner(file);
while (inputStream.hasNext()) {
String data =inputStream.next();//this line is useless but the program doesn't display with out it
String[] values = data.split(",");//this line is useless but the program doesn't display with out it
i++;//this line is useless but the program doesn't display with out it
line++;
}
}catch(FileNotFoundException e){
e.printStackTrace();
}
return line;
}
Use BufferedReader instead of Scanner:
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
while(reader.readLine() != null){
line++;
}
public static int getLineCount(){
String csvFilePath = "C:\\Users\\uzochi\\desktop\\txt.csv";
String line = "";
int numberOfLines=0;
try {
BufferedReader br = new BufferedReader(new FileReader(csvFilePath));
while (( line = br.readLine()) != null) {
numberOfLines++;
}
}catch(FileNotFoundException e){
//
}catch (IOException ex) {
//
}
return numberOfLines;
}
I am having some very wierd issues while attempting to read a file.
Its only a few lines of simple code, but for some reason its thinking that my file has 8 lines of wierd rumbo jumbo text, while it has 2 lines and 4 letters in each line.
Code (Executed once, it's reading the correct file)
Scanner scanner = null;
ArrayList<String> lines = new ArrayList<String>();
try {
scanner = new Scanner(getClass().getResourceAsStream("/level.txt"));
} catch (Exception ex) {
ex.printStackTrace();
}
while (scanner.hasNext()) {
lines.add(scanner.nextLine());
}
Main.main.log(lines.size() + " size");
File (level.txt, with no spaces)
sssas
sssas
Output:
8 Size
Its super weird since it's only a few lines and a simple file.
Any help, suggestions or error's made? There are no stacktraces!
Thanks,
Jake
Java 7 one-liner to read a file to a list:
List<String> lines = Files.readAllLines(
Paths.get(getClass().getResource("/level.txt").toURI()),
StandardCharsets.UTF_8
);
The first issue to consider is as #Sotirios Delimanolis says, you may read from a wrong txt file.
The second issue is that if you are perfectly sure about reading from the correct .txt file, the solution is to read with reading scanner.hasNextLine() while appending to the "lines" variable.
I think the problem occurs when you read with "hasNext()" which reads token by token, and go into next step with "scanner.nextLine()" which goes to the next line.
For example you may use the following;
Scanner scanner = null;
ArrayList<String> lines = new ArrayList<String>();
try {
scanner = new Scanner(getClass().getResourceAsStream("/level.txt"));
} catch (Exception ex) {
ex.printStackTrace();
}
while (scanner.hasNextLine()) { /* difference is here */
lines.add(scanner.nextLine());
}
Main.main.log(lines.size() + " size");
EDIT:
You can use the following code and modify it however you want.
I think the problem is also occurs when you are reading the File. To read the file you can use new File() constructor instead of your choice. See below:
Scanner scanner = null;
ArrayList<String> lines = new ArrayList<String>();
try {
scanner = new Scanner(new File("level.txt")); /* difference is here */
} catch (Exception ex) {
ex.printStackTrace();
}
while (scanner.hasNextLine()) { /* difference is here */
lines.add(scanner.nextLine());
}
System.out.println(lines.size()); // gives output 2.
I would suggest to go on different kind of method which is more correct to do..
public static void main(String[] args) {
BufferedReader br = null;
ArrayList<String> lines = new ArrayList<String>();
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
lines.add(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
This will do the trick perfectly.. hope that helps
EDIT:
If you would like to read file from classpath of the project you can use the following:
InputStream in = this.getClass().getClassLoader().getResourceAsStream("SomeTextFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in, "UTF-8"));
Somethink like that will be fine.. I am not saying you cannot do it with scanner.. IMHO I think this is better.. But it is a matter of choice and not big architecture problem.. Consideration is yours :)
I'm writing a mock stock market in Java, and I want the ability for the user to view stocks purchased. I decided the easiest way to do this is to write to a file. My problem is that every time I run this program and attempt to read from the file, it outputs the path it took to read it. The information I want is correctly written to the file, but it isn't reading from it the way I want.
Here is the code I used for the file reading section:
if (amountOfStocks1 >= 1) {
Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");
while (stocksBought1.hasNext()) {
String fileRead = stocksBought1.nextLine();
System.out.println(fileRead);
}
stocksBought1.close();
runMenu = 1;
}
There are 7 of these amountOfStocks if/else statements.
I'm not sure if that's enough information. If it's not, tell me what to put on, and I'll do that.
If you can help me fix this problem or if you know an easier way to read and write to files that would be great!
Instead of:
Scanner stocksBought1 = new Scanner("stocksbought/stocksBought1.txt");
Try:
Scanner stocksBought1 = new Scanner(new File("stocksbought/stocksBought1.txt"));
When you only pass a String to the Scanner constructor the Scanner just scans that String. If you give it a File it will scan the contents of the File.
You would probably be better off using the FileReader object. You would use code similar to the following:
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception
{
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
}
In addition, you can use the FileWriter object to write to a file. There's lots of examples on the internet. Easy to find on simple Google search. Hope this helps.
Use FileReader.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class BufferedReaderExample {
public static void main(String[] args) {
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\testing.txt"));
while ((sCurrentLine = br.readLine()) != null) {
System.out.println(sCurrentLine);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.