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 :)
Related
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.
I am trying to replace ? with - in my text document but just the ArrayList<String> is being written in the new file without all lines of the old one. How can I fix that?
File file = new File("D:\\hl_sv\\L09MF.txt");
ArrayList<String> lns = new ArrayList<String>();
Scanner scanner;
try {
scanner = new Scanner(file);
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
// System.out.println("I found it on line " + lineNum);
}
}
lines.clear();
lines = lns;
System.out.println("Test: " + lines);
FileWriter writer;
try {
writer = new FileWriter("D:\\hl_sv\\L09MF2.txt");
for (String str : lines) {
writer.write(str);
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I don't understand why you're storing the lines in a List to begin with. I would perform the transform and print while I read. You don't need to test for the presence of the ? (replace won't alter anything if it isn't present). And, I would also use a try-with-resources. Something like
File file = new File("D:\\hl_sv\\L09MF.txt");
try (PrintWriter writer = new PrintWriter("D:\\hl_sv\\L09MF2.txt");
Scanner scanner = new Scanner(file)) {
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
writer.println(line.replace('?', '-'));
}
} catch (Exception e) {
e.printStackTrace();
}
Examine this code:
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
}
You are only adding the current line (with the replacement) if it had a ? in it, ignoring other lines. Restructure it to always add the existing line.
if (line.contains("?")) {
line = line.replace("?", "-");
}
lns.add(line);
Additionally, the part
if (line.contains("?"))
scans line to look for a ?, and then the code
line.replace("?", "-");
does the same thing, but this time also replacing any ? with -. You may as well scan line just once:
lns.add(line.replace("?", "-"));
Note that creating an ArrayList just to hold the new lines wastes a fair amount of memory if the file is large. A better pattern would be to write each line, modified if necessary, right after you read in the corresponding line.
Within your while loop you have an if statement checking the line which adds the altered line to the array. You also need to add the unaltered lines to the array.
This should fix your issue:
int lineNum = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
lineNum++;
if (line.contains("?")) {
line = line.replace("?", "-");
lns.add(line);
// System.out.println("I found it on line " + lineNum);
}
else{
lns.add(line);
}
Previously, you were only adding the line to your ArrayList if it contained a "?" character. You need to add the line to the ArrayList whether or not it contains "?"
I would use a different approach if I'm trying to work on the functionality you want to implement, please check this approach and tell me if this helps you :)
public void saveReplacedFile() {
//1. Given a file in your system
File file = new File("D:\\hl_sv\\L09MF.txt");
try {
//2. I will read it, not necessarily with Scanner, but use a BufferedReader instead
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
//3. Define a variable that will hold the value of each line
String line = null;
//and also the information of your file
StringBuilder contentHolder = new StringBuilder();
//why not get your line separator based on your O.S?
String lineSeparator = System.getProperty("line.separator");
//4. Check your file line by line
while ((line = bufferedReader.readLine()) != null) {
contentHolder.append(line);
contentHolder.append(lineSeparator);
}
//5. By this point, your contentHolder will contain all the data of your text
//But it is still a StringBuilder type object, why not convert it to a String?
String contentAsString = contentHolder.toString();
//6. Now we can replace your "?" with "-"
String replacedString = contentAsString.replace("?", "-");
//7. Now, let's save it in a new file using BufferedWriter :)
File fileToBeSaved = new File("D:\\hl_sv\\L09MF2.txt");
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(fileToBeSaved));
bufferedWriter.write(replacedString);
//Done :)
} catch (FileNotFoundException e) {
// Exception thrown if the file does not exist in your system
e.printStackTrace();
} catch (IOException e) {
// Exception thrown due to an issue with IO
e.printStackTrace();
}
}
Hope this is helpful. Happy coding :)
If you can use Java 8 then your code can be simplified to
try (PrintStream ps = new PrintStream("D:\\hl_sv\\L09MF2.txt");
Stream<String> stream = Files.lines(Paths.get("D:\\hl_sv\\L09MF.txt"))) {
stream.map(line -> line.replace('?', '-')).forEach(ps::println);
} catch (IOException e) {
e.printStackTrace();
}
I've tried to read a text file and try to modify it. So many discussion that I got from StackOverflow, here is the content:
NO 1025 0
NO 1025 1
OP 1026 0
EndRow
The modified text file that I want:
NO 0
AND 1
OP 0
EndRow
I read some discussion topics about it, and then came the conclusion that I have to use the .hasNextLine method to check every line. Here's the code:
import java.io.*;
import java.util.Scanner;
public class MainConvert {
/**
* #nahdiya
*/
public static void main(String[] args) {
try {
File readNet = new File("testttt.net");
FileReader readFileNet = new FileReader(readNet);
BufferedReader reader = new BufferedReader(readFileNet);
Scanner scan = new Scanner("testttt.net");
PrintWriter fileConvert = new PrintWriter("convertNet.txt");
while (scan.hasNextLine()) {
String check = scan.next();
String checkLine = scan.nextLine();
if (checkLine.contains("NO 1025")) {
if(checkLine.contains("NO 1025")) {
fileConvert.println("AND "+check );
} else if (checkLine.contains("OP 1026")) {
fileConvert.println("OP"+check);
} else {
fileConvert.println(checkLine);}
}
}
}
reader.close();
fileConvert.close();
} catch(Exception ex) {
ex.printStackTrace();
}
}
When I tried to run the class, an output message appeared like this:
java.util.NoSuchElementException: No line found
at java.util.Scanner.nextLine(Unknown Source)
at fileConvertSave.MainConvert.main(MainConvert.java:21)
The problem is:
PrintWriter fileConvert = new PrintWriter("convertNet.txt");
What is the problem with this line? I just want to modify the testttt.net file. fileConvert must be created as the new file. What is wrong with it?
Edited: See the full solution at the bottom:
The original problem that was yielding the error message was the Scanner trying to perform nextLine() on a line that wasn't there due to:
String check = scan.next();
String checkLine = scan.nextLine();
When you call:
while( scan.hasNextLine() )
there is a next line available. You then call:
scan.next();
At this point there might not be a "next line" available anymore. You then call:
scan.nextLine()
and boom.
removing the line
String check = scan.next();
should work.
Edit:
Here is a solution to all the other parts of the problem... It's basically a complete rewrite of what you've got, so please read all the code, learn what it does and try to understand it all! If in doubt, please read the documentation first before asking a question.
BufferedReader reader = null;
PrintWriter writer = null;
try {
reader = new BufferedReader(new FileReader("testttt.txt"));
writer = new PrintWriter("convertNet.txt");
// setup the pattern that we want to find and replace in the input:
// NB> this is a regex (or regular expression)
// it means, find [space] then either 1025 or 1026 then [space]
String patternToMatch = " (1025|1026) ";
String inputLine = null;
// while there are lines to read, read them one at a time:
while ((inputLine = reader.readLine()) != null) {
// create the outputLine which is the input line with our pattern
// " 1025 " or " 1026 " replaced by just a single space:
String outputLine = inputLine.replaceFirst(patternToMatch, " ");
// log the transformation for debugging purposes:
System.out.println(inputLine + " -> " + outputLine);
// write the outputLine to the output file:
writer.println(outputLine);
}
}
catch (FileNotFoundException ex) {
System.out.println("file was not found: " + ex);
}
catch (IOException ex ) {
System.out.println("io error: " + ex);
}
finally {
try {
if( reader != null ) reader.close();
if ( writer != null ) writer.close();
} catch (IOException ex) {
System.out.println("error closing file " + ex);
}
}
Note that the finally block cleans up nicely even in the event there is an Exception. There's also a newer way to do this, that can make code a little shorter called try with resources:
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Your string does not look consistent i recommend you use regex if there are more strings like this and Bufferreader to read line, although i didn't use regex but this what i came up with,
public static void main(String[] args) {
try {
File readNet = new File("testttt.net");
FileReader readFileNet = new FileReader(readNet);
BufferedReader reader = new BufferedReader(readFileNet);
PrintWriter fileConvert = new PrintWriter("convertNet.txt");
String r = null;
while ((r = reader.readLine()) != null) {
System.out.println(r);
if (r.equals("NO 1025 1")) {
fileConvert.println(r.replace(r, "AND 1"));
} else if (r.contains("1025 0")) {
fileConvert.println(r.replaceAll("1025", ""));
} else if (r.contains("1026")) {
fileConvert.println(r.replaceAll("1026", ""));
} else {
fileConvert.println(r);
}
}
reader.close();
fileConvert.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
Good Luck, i hope it helps you.
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);
I've made a GUI and a button.
My code looks like this:
private void jButtonSubmitActionPerformed(java.awt.event.ActionEvent evt) {
try {
Scanner scan = new Scanner(new File("persontest.txt"));
while(scan.hasNext()) {
System.out.println(scan.nextLine());
}
} catch (FileNotFoundException ex) {
System.out.println("File not found" + ex.getMessage());
} catch (Exception e) {
System.out.println("Some error" + e.getMessage());
}
persontest.txt contains the following text:
What do I contribute with when working in team work:
a. I come up with new ideas
b. I follow-up on things because I'm basically
thorough
c. I assess what is realistic and workable
d. I advocate alternative approaches objectively and unbiased
When trying to run I get "Some error No line found"
I tried removing all special characters from the text and I could read it, so I tried adding "UTF-8" to my scanner in this manner.
Scanner scan = new Scanner(new File("persontest.txt"), "UTF-8");
However this does not seem to do anything. I still get "No line found".
If this question has been asked before excuse me, I did a thorough search, but I either could not comprehend the question asked or the answer provided in context to my problem.
I changed my scanner to bufferedreader per Troubleshoot and Harshas example and it will now read the text even with special chars, however it won't display them correctly. I just get square boxes. It's a minor problem.
If persontest.txt is in classpath (i.e. inside jar or source folder) you can use:
YourClass.class.getClassloader().getResourceAsStream("persontest.txt")
First of all, make sure persontest.txt is in your main project folder, and not a sub-folder of that, as it will not find it otherwise.
I recommend using a BufferedReader to read it line by line. Here's how:
BufferedReader input = new BufferedReader(new FileReader("persontest.txt"));
String line;
while ((line = input.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
}
It's good practice to check that the line isn't empty along with checking it isn't equal to null. For example, if a line was equal to \t it would be classed as empty, but not as null.
You could simply do this using
try {
String line;
BufferedReader br = new BufferedReader(new FileReader("persontest.txt"));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
if you need to do it with a Scanner you can try using
Scanner reader = new Scanner(new FileInputStream("persontest.txt");