Splitt several JSON Strings in a single Line - java

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.

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();
}

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

Android Development - Using Inputstream/BufferStream, how do I throw all the lines of a text file into an array?

This is another question. So it seems that I have already set up the code with InputStream and Bufferstream to retrieve a String from a text file using this code:
// Read Text File entitled wordsEn.txt
public String readFromFile() {
String words = "";
try {
InputStream inputstream = openFileInput("wordsEn.txt");
if (inputstream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputstream.close();
words = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
return words;
}
So what I want to do is store each string on each line of the text file into an array. I then want to be able to use this array to select a random string everytime I press a button.
Let me know.
Thanks
Colin
Just put below line into your class varialble
ArrayList<String> wordLineArray = new ArrayList<String>();
Than use add method array list to add each line of word into it.
wordLineArray.add(receiveString);
Use this line before appending it to previous buffer.
Now use this arraylist as per your requirment.
If it is helpful to you than don't forget to accept this answer.
Try using BreakIterator.getLineInstance(). Set the text to your "words" string, then iterate through each line, adding each line to a String[] array.

Collections sort not working properly

I am new to Java. I am trying to added few words from a text file to my existing text based word list. I have the below code doing
Add words from an file to existing list
Sort the list of words
Save the words to a text file
"wordList" is an arraylist with existing words.
private void updateDictionaryFile(String filepath) {
String textCurrentLine = "";
BufferedReader dictionaryFile = null;
try {
Scanner fileScanner = new Scanner(new File(filepath));
while(fileScanner.hasNextLine()){
System.out.println("fileScanner.hasNextLine() "+ fileScanner.hasNextLine());
textCurrentLine = fileScanner.nextLine();
if(textCurrentLine.length() > 0)
if (!wordList.contains(textCurrentLine)) {
wordList.add(textCurrentLine);
}
}
Collections.sort(wordList);
String newFile = filepath.replace(".txt", "_new.txt");
PrintWriter pw = new PrintWriter(new FileOutputStream(newFile));
for (int i = 0; i < wordList.size(); i++) {
pw.println(wordList.get(i).toString());
}
pw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (dictionaryFile != null) {
dictionaryFile.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
Word listed in new file is not sorted. Am I missing something in between?
Below is the output
A
Achieve
Although
Anything
Ask
Avoid
Badly
Bluma
But
Find
Forget
Goal
Goals
How
In
It
Just
Keep
Know
NOT
Often
Once
One
Psychologists
Reasoning
Reject
Remember
Research
Russian
Shifting
Sidestep
So
Sometimes
Start
Stop
The
This
Those
Under
Visualise
Visualising
We
What
When
With
You
Zeigarnik
a
aa
aah
aahed
aahing
aahs
aal
aalii
aaliis
aals
aardvark
aardwolf
aargh
aarrgh
aarrghh
aas
Collections.sort(wordList); will work perfectly. if need to ignore the case then use below code.
Collections.sort(wordList,String.CASE_INSENSITIVE_ORDER);

Efficiency while reading a txt file to an array

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?

Categories

Resources