Reading arraylist from a .txt file - java

I have an app where user inputs certain words and those words are saved to a .txt file on the device. Then I'm creating arraylist from that .txt file. This is the code:
try {
Scanner s = new Scanner(recordedFiles);
recordedFilesArray = new ArrayList<String>();
while (s.hasNext()){
recordedFilesArray.add(s.next());
}
s.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now, the problem is that this puts each word to arraylist, not each line. So if user inputs (for example) 'test1', it'll add it to arraylist as test1 (which is fine), but if user inputs 'test 1' (with a space), 'test' and '1' will be added to arraylist as seperate elements.
Showing an example how it should work:
How text file looks like (example)
test 1
test 2
test 3
How arraylist looks like now:
test
1
test
2
test
3
How arraylist should look like:
test 1
test 2
test 3
So my question is; how do I add LINES to arraylist, not seperate words from a .txt file

Use .nextLine() which functions as follows:
Advances this scanner past the current line and returns the input that
was skipped. This method returns the rest of the current line,
excluding any line separator at the end. The position is set to the
beginning of the next line.
As Matt Ball has indicated the while loop should use hasNextLine() instead of hasNext()
try {
Scanner s = new Scanner(recordedFiles);
recordedFilesArray = new ArrayList<String>();
while (s.hasNextLine()){
recordedFilesArray.add(s.nextLine());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
s.close(); //close file on success or error
}
Documentation

Use Scanner#hasNextLine() with Scanner#nextLine(), not Scanner#hasNext() with Scanner#next().

You can use scanner.nextLine();

Instead of using scanner.next(); use scanner.nextLine();

Related

How can I get Java to read all text in file?

I am trying to get Java to read text from a file so that I can convert the text into a series of ascii values, but currently it only seems to be reading and retrieving the first line of the txt file. I know this because the output is much shorter than the text in the file.
The text in the file is below:
AD Mullin Sep 2014 https://hellopoetry.com/poem/872466/prime/
Prime
Have you ever thought deeply about Prime numbers?
We normally think of prime as something unbreachable
In base ten this is most likely true
But there are other languages that might be used to break down numbers
I'm no theorist but I have my theories
What was behind the Big Bang?
Prime
If impermeable ... then the Big Bang never happened
And any good programmer worth a lick of salt, always leaves a back door
So, I bet there are some Prime numbers out there that are permeable, otherwise ...
We wouldn't be the Children of the Big Bang
I think because each line of text has an empty line between them the program is only reading the first line then stopping when it sees there is no line after it, but in facts 2 lines down instead.
Here is the code I have written:
package poetry;
import java.io.FileNotFoundException;
import java.util.Formatter;
import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.FileWriter;
public class poetry {
public static void main(String[] args) {
// TODO Auto-generated method stub
//Below try catch block reads file text and encodes it.
try {
File x = new File("/Users/jordanbendon/Desktop/poem.txt");
Scanner sc = new Scanner(x);
//Right below is where I think the issue lies!
while(sc.hasNextLine()) {
String lines = sc.nextLine();
char[] stringArray = lines.toCharArray();
String result = "";
for (int i = 0; i < lines.length(); i++) {
int ascii = lines.codePointAt(i);
if ((ascii >= 65 && ascii <= 90) || (ascii >= 97 && ascii <= 122)) {
ascii += 15;
result += Integer.toString(ascii);
} else {
result += stringArray[i];
}
}
System.out.println(result);
//Try catch block here creates a new file.
try {
File myObj = new File("/Users/jordanbendon/Desktop/EncryptedMessage.txt");
File s = myObj;
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
break;
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
//Try catch block here writes the new encrypted code to the newly created file.
try {
FileWriter myWriter = new FileWriter("/Users/jordanbendon/Desktop/EncryptedMessage.txt");
myWriter.write(result);
myWriter.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}}
catch(FileNotFoundException e) {
System.out.println("error");
}
}
}
I have commented in the code where I think the issue is. The first while condition checks whether there is a next line by using the hasNextLine(), I have tried using the method ReadAllLines() but it says this method is undefined for the type scanner.
How can I get the program to read and retrieve the entire text file instead of the first line?
Thanks!
To read the entire input stream:
Scanner sc = new Scanner(x).useDelimiter("\\A");
then just:
String entireInput = sc.next();
This works by setting the token delimiter to start of all input, which of course is never encountered after any byte read, so the "next" token is the entire input.
For each execution you check whether the hard coded file name was created or already exists. In case it already existed you happen to break the loop which halts the execution from progressing.
https://www.javatpoint.com/java-break

OutputStreamWriter only writing one item into file

I have used the following code to write elements from an arraylist into a file, to be retrieved later on using StringTokenizer. It works perfect for 3 other arraylists but somehow for this particular one, it throws an exception when reading with .nextToken() and further troubleshooting with .countTokens() shows that it only has 1 token in the file. The delimiters for both write and read are the same - "," as per the other arraylists as well.
I'm puzzled why it doesnt work the way it should as with the other arrays when I have not changed the code structure.
=================Writing to file==================
public static void copy_TimeZonestoFile(ArrayList<AL_TimeZone> timezones, Context context){
try {
FileOutputStream fileOutputStream = context.openFileOutput("TimeZones.dat",Context.MODE_PRIVATE);
OutputStreamWriter writerFile = new OutputStreamWriter(fileOutputStream);
int TZsize = timezones.size();
for (int i = 0; i < TZsize; i++) {
writerFile.write(
timezones.get(i).getRegion() + "," +
timezones.get(i).getOffset() + "\n"
);
}
writerFile.flush();
writerFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
==========Reading from file (nested in thread/runnable combo)===========
public void run() {
if (fileTimeZones.exists()){
System.out.println("Timezone file exists. Loading.. File size is : " + fileTimeZones.length());
try{
savedTimeZoneList.clear();
BufferedReader reader = new BufferedReader(new InputStreamReader(openFileInput("TimeZones.dat")));
String lineFromTZfile = reader.readLine();
while (lineFromTZfile != null ){
StringTokenizer token = new StringTokenizer(lineFromTZfile,",");
AL_TimeZone timeZone = new AL_TimeZone(token.nextToken(),
token.nextToken());
savedTimeZoneList.add(timeZone);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}
===================Trace======================
I/System.out: Timezone file exists. Loading.. File size is : 12373
W/System.err: java.util.NoSuchElementException
at java.util.StringTokenizer.nextToken(StringTokenizer.java:349)
at com.cryptotrac.trackerService$1R_loadTimeZones.run(trackerService.java:215)
W/System.err: at java.lang.Thread.run(Thread.java:764)
It appears that this line of your code is causing the java.util.NoSuchElementException to be thrown.
AL_TimeZone timeZone = new AL_TimeZone(token.nextToken(), token.nextToken());
That probably means that at least one of the lines in file TimeZones.dat does not contain precisely two strings separated by a single comma.
This can be easily checked by making sure that the line that you read from the file is a valid line before you try to parse it.
Using method split, of class java.lang.String, is preferable to using StringTokenizer. Indeed the javadoc of class StringTokenizer states the following.
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is discouraged in new code. It is recommended that anyone seeking this functionality use the split method of String or the java.util.regex package instead.
Try the following.
String lineFromTZfile = reader.readLine();
while (lineFromTZfile != null ){
String[] tokens = lineFromTZfile.split(",");
if (tokens.length == 2) {
// valid line, proceed to handle it
}
else {
// optionally handle an invalid line - maybe write it to the app log
}
lineFromTZfile = reader.readLine(); // Read next line in file.
}
There are probably multiple things wrong, because I'd actually expect you to run into an infinite loop, because you are only reading the first line of the file and then repeatedly parse it.
You should check following things:
Make sure that you are writing the file correctly. What does the written file exactly contain? Are there new lines at the end of each line?
Make sure that the data written (in this case, "region" and "offset") never contain a comma, otherwise parsing will break. I expect that there is a very good chance that "region" contains a comma.
When reading files you always need to assume that the file (format) is broken. For example, assume that readLine will return an empty line or something that contains more or less than one comma.

Writing file to array it writes only last record in my array

I want to print my console lines to txt file.I want this operation in else statement.But it writes to file only last record.How can i fixed it? When i try buffered reader it cant solve my problem.Thanks everybody.Have a good day.Which solution do you advice to me?
for(int iy=0;iy<arr.length;iy++){
if( arr[iy].contains("•") || arr[iy].contains("Contact") || arr[iy].contains("#") || arr[iy].contains("Activities and Societies") || arr[iy].contains("Page")){
}
else if(arr[iy].contains("Summary")){
//System.out.println(arr[iy]+"enes");
while(exit==false){
iy++;
if(arr[iy].contains("Experience")){
exit=true;
}
}
}
else if(arr[iy].contains("Skills") || arr[iy].contains("Languages")){
while(exit==false){
iy++;
if(arr[iy].contains("Education")){
exit=true;
}
}
}
else
{
System.out.println(arr[iy]);
try(PrintWriter bw = new PrintWriter(new FileWriter(FILENAME2))){
bw.write(arr[iy]);
//out.newLine();
bw.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Your code is very convoluted, but the reason for just the last line being written is clear - you open the file for each line you are about to output to it, and overwrite the previous contents of the file.
You shouldn't open and close the file for each line. Open it once before the loop, and close it after the loop.
If it did make sense to open and close the file multiple times, you should have opened the FileWriter in append mode (by using new FileWriter(FILENAME2,true)).
Looks like you're re-creating the PrintWriter at every step of the loop, which overwrites the file. Create it before the loop and close it afterwards.

java.util.NoSuchElementException when using Scanner.next()

Java noob working on a project where I'm supposed to display data obtained from a text file onto grids. Project is essentially written, but output displays this exception:
run:
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50)
at boggle.Boggle.main(Boggle.java:27)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
Boggle.java:27 links to a line of code in the main method of my superclass Boggle.java. The line is supposed to call one of the methods in my class ReadDataFile.java. The line reads dataRead.populateData(); (//2. on the comments below), and in context the main method looks like:
public static void main(String[] args) { //main() method begins
// TODO code application logic here
ReadDataFile dataRead = new ReadDataFile("BoggleData.txt"); //1. instance of class ReadDataFile created
dataRead.populateData(); //2. populateData() method called
boggleData = dataRead.getData(); //3. member variable set equal to getData() method
Board boggleBoard = new Board(boggleData); //4. instance of class Board created, passing data as argument
boggleBoard.shakeDice(); //5. shakeDice() method called
} //main() method ends
ReadDataFile.java:50 links to a line in a method called populateData() inside of my subclass ReadDataFile.java. The line is input.next(); and it's in the finally component of a try-catch-finally I created for the class. In context, the populateData() method looks like:
public void populateData(){ //populateData() method begins
try{ //try begins
URL url = getClass().getResource(dataFile); //1. instance of class URL created from file name
File file = new File(url.toURI()); //2. instance of class File based on url
input = new Scanner(file); //3. member variable initialized based on file
while(input.hasNext()){ //4. while loop goes through data file
data.add(input.next()); //a. data from file added to ArrayList
}
} //try ends
catch(Exception ex){ //catch begins
System.out.println(ex.toString());
ex.printStackTrace();
} //catch ends
finally{ //finally begins
input.next();
} //finally ends
} //populateDate() method ends
Basically, I'm having trouble figuring out how I can get around this exception. The actual goal of the project is to display data in grids, but I only get a notice that an exception has been found in the output. The code compiles fine, so I'm not worried about misplaced semicolons or incorrect data types. I'm new to the Java language, and while books and other stackoverflow questions have solved some of my problems, this exception has gotten me stuck.
Would anybody be able to provide some feedback on just what I need to do to get around the exception showing up in my output, what's causing it, or at least steer me in the right direction? I'd really appreciate any helpful comments. Thanks.
Your exception stack-trace shows where the problem is:
at inputOutput.ReadDataFile.populateData(ReadDataFile.java:50)
At line 50 you have this:
finally{ //finally begins
input.next();
}
The problem is that you have already exhausted the file with a loop you previously executed:
while(input.hasNext()){ //4. while loop goes through data file
data.add(input.next()); //a. data from file added to ArrayList
}
I think you meant to close in your finally.
finally{ //finally begins
input.next();
}
should (almost certainly) be
finally{
input.close();
}
Or you could use try-with-resources to close your Scanner like
public void populateData(String dataFile) {
try {
URL url = getClass().getResource(dataFile);
File file = new File(url.toURI());
try (Scanner input = new Scanner(file)) {
while (input.hasNext()) {
data.add(input.next());
}
}
} catch (Exception ex) {
System.out.println(ex.toString());
ex.printStackTrace();
}
}

String to Text - Line Break instead of comma

I need help before I'm totally despaired :D
As you will see I tried it in different ways even if there are just a really few differences. My problem is that I have a string which I want (or have) to output. This means I need it in a text file. Not that big problem, eh? But the actual problem is that I want line breaks instead of commas. I know I could just replace them after the file is written but it's just unnecessary when there is another way.
The Output looks like this
[/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus,
/rechtschreibung/_Ndrangheta, ....]
I want it to look like this
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Anyway even when I don't need this method later because I will store this and some other information into a database like sql. It will help me to build up the program step by step and learn some more Java ;)
So here is my code snippet
BufferedWriter bw = null;
//PrintWriter out
//= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
try {
bw = new BufferedWriter(new FileWriter("bfwr.txt"));
bw.write(test5.getWoerterListe().toString());
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
try {
PrintWriter out = new PrintWriter(new FileWriter("prwr.txt"));
out.print(test5.getWoerterListe());
out.close();
System.out.printf("Testing String");
} catch (IOException e) {
e.printStackTrace();
}
*/
/*
try {
FileWriter test10 = new FileWriter("test.txt");
test10.write(test5.getWoerterListe().toString());
test10.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
Please be nice to me :D
Assistance appreciated =)
EDIT #1
Code directly before first one.
Oberordner test2 = new Oberordner("http://www.duden.de/definition");
Unterordner test3 = new Unterordner(test2.getOberOrdner());
WoerterListe test5 = new WoerterListe(test3.getUnterOrdnerURL());
test5.setWoerterListe();
and from WoerterListe.java the really end part
public ArrayList<String> getWoerterListe(){
return WoerterListe;
}
Additional Information: the string is not stored in the code because there are tenthousands of words like '/rechtschreibung/*'
By the way the language here is german unfortunately I have to use german words =(
I'm not a Java developer and you didn't state what getWoerterListe() returns, but here's my guess.
getWoerterListe() probably return a list of strings, and the default behaviour of toString() in this case is to convert the list to comma seperated values. So instead of calling toString() on the list, loop through it and write out each line followed by a carriage return (or whatever Java uses to end lines).
Code:
String s = "[/rechtschreibung/_n, /rechtschreibung/_nauf, "
+ "/rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....]";
String srp = s.replaceAll("\\[|\\]|\\.+" ,"");
String[] sp = srp.split(",");
for (int i = 0; i < sp.length; i++) {
System.out.println(sp[i].trim());
}
Output:
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Explanation:
I assumed [/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....] is a String. I removed all uncessary character like [ , ] , and any number of . form it. After that, I splited by , and print each element of splited string on the output.

Categories

Resources