Efficiency while reading a txt file to an array - java

I have written a script in which I read in .txt files to arrays. It works perfectly but I'm curious if there is a more efficient way of reading the .txt files in.
I have this:
try {
String line;
filestart = new BufferedReader(new FileReader("C:\\path\\file.txt));
for (line = filestart.readLine(); line !=null; line = filestart.readLine()) {
array.add (line);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Is there a function that combines BufferedReader and FileReader?
How would Scanner compare with what I have?

Related

Read the first number in a line, move on to next line without reading the rest of the line until end of file

I am reading from a txt file. It has stuff in it like...
2 // Two
3
40 // oh look, forty
Currently the output looks like this...
2
//
Two
3
40
//
oh
look,
forty
I don't want that. I just want the integers, so the output should be...
2
3
40
I want to read just the integer at the beginning of the line, ignore the rest of the line then move to the next line. I will keep doing this until I reach the end of the file. Ultimately all these integers will go into an array.
try {
File program = new File("file.txt");
Scanner myReader = new Scanner(program);
while (myReader.hasNextLine()) {
String data = myReader.next();
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("File not Found.");
e.printStackTrace();
}
I have tried BufferedReader but I think it can't do what I want it to do, so I went with a Scanner. If it matters here is my attempt with that.
try {
BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = reader.()) != null)
System.out.println(line);
reader.close();
} catch (IOException e) {
System.out.println("File not Found.");
e.printStackTrace();
}
Considering you want only the first number found in a line of text, I'll use Scanner.nextInt.
try {
File program = new File("file.txt");
Scanner myReader = new Scanner(program);
while (myReader.hasNextLine()) {
Integer data = myReader.nextInt();
myReader.nextLine(); // avoid reading 7 as nextInt. eg. "5 // seven 7"
System.out.println(data);
}
myReader.close();
} catch (FileNotFoundException e) {
System.out.println("File not Found.");
e.printStackTrace();
}

BufferedReader issue: String and Numeric values from a .txt are being retrieved as null and zeros

I have tried to get string and numeric values from a text file using BufferedReader. Apparently, it is recognizing the number of records (lines) of the text file, but the values are not being retrieved as they are. String ones are being placed as "null" and double as zeros. I am kind of new in Java and I would like to know the possible reason of this output and also how could I solve it.
I tried to adapt the results to an arraylist as part of a table visualization, however after some tries it was not possible solve the problem:
private ArrayList<ListClasses> seeListe() {
ArrayList<ListClasses> list = new ArrayList<>();
File file = new File("C:/file/to/path/file.txt");
BufferedReader br = null;
try {
FileReader fr = new FileReader(file);
BufferedReader breader = new BufferedReader(fr);
String line = breader.readLine();
while (line != null) {
list.add(new ListClasses());
line = breader.readLine();
}
} catch (FileNotFoundException e) {
System.out.println("File not found: " + file.toString());
} catch (IOException e) {
System.out.println("Unable to read file: " + file.toString());
}
finally {
try {
br.close();
} catch (IOException e) {
System.out.println("Unable to close file: " + file.toString());
}
catch(NullPointerException ex) {
}
}
return list;
}
The records in you file should really represent one object so your class name shouldn't be a plural, but if your ctor is right, you can just do:
List<ListClasses> data = Files.lines(Paths.get(pathToDataFile)).map(ListClasses::new).collect(Collectors.toList());

Splitt several JSON Strings in a single Line

I have a txt-file which is a single line with several JSON Strings. My problem is that i don't know how to get every JSON Object.
try {
FileReader fr = new FileReader("SelectedChoice.txt");
BufferedReader br = new BufferedReader(fr);
String zeile ="";
while((zeile = br.readLine())!=null) {
System.out.println(zeile);
JSONObject choice = new JSONObject(zeile);
System.out.println(choice);
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
This is the String which have to converted:
{"Item":"MasterNode","Choice 1":1,"Choice 2":0,"Choice 3":-1}{"Item":"WorkerNode","Choice 1":1,"Choice 2":0,"Choice 3":-1}
This code only converts the first JSON String in the line, whilst I want to convert all of them.
So I pulled it up in my IDE and downloaded the org.json library and it ran just fine. Because of the way you read the file, it may be that you are loosing one line and just keeping the last line. If you want to save the JSONObject, You could always try saving the JSONObject in an ArrayList or some other collection such as this...
Collection<JSONObject> JSONObjects = new ArrayList<>();
try {
FileReader fr = new FileReader("SelectedChoice.txt");
BufferedReader br = new BufferedReader(fr);
String zeile ="";
while((zeile = br.readLine())!=null) {
System.out.println(zeile);
JSONObject choice = new JSONObject(zeile);
System.out.println(choice);
JSONObjects.add(choice);
}
br.close();
fr.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You could than access the Collection after your file is finished being read.
Hope this helps! Good Luck!
P.S. If you have any other questions feel free to ask!
Edit
So I just read in the comments above that you thought it should be one line. If >you want the too groups to be separate, you might want to put the new line >back. If you want that to be one JSONObject, you might be running into a >syntax error. Try adding a , in between the two groups of values.

Java File Reading Issues

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 :)

Read cyrillics and non-cyrillics characters from file java

I have a file with cyrillics and non-cyrillics characters. However, when I read the file the cyrillics characters are not retrived and non-cyrillics characters are retrived. Here is the code I am using
private static String dirToPRocess = "D:\\stopwords_freq_v2.txt";
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(new FileInputStream(
dirToPRocess), "UTF-8"));
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Are you using eclipse?
You can try the following to get it to work:
save your java file with the character encoding utf-8.
If you want to print cyrillics to the console, I think there might be a setting in eclipse's properties somewhere that does that but not 100% certain- it should print cyrillics by default in my experience.
Your java code looks OK btw.

Categories

Resources