ReadLine (Buffered reader) does not work in a loop [duplicate] - java

This question already has answers here:
Kotlin readln() does not work as intended
(1 answer)
Intellij Idea scanner.nextLine() returns empty String
(1 answer)
Closed 9 months ago.
I'm writing code in Intelij. readLine does not correctly read the input (puts a line break at the end of the line), which is why the next readline does not work (becomes automatically empty).
Code:
public class Start {
public static void main(String[] args) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String s = reader.readLine();
ArrayList<String> list = new ArrayList<>();
while (true) {
if (s == null || s.isEmpty()) {
break;
}
else list.add(s);
s = reader.readLine();
}
for (String str : list) {
System.out.println(str);
}
If important: LF separator and UTF-8 encoding

It's a known bug in IntelliJ IDEA. The fix is already available, please update.

Related

Add one whitespace at everyline of my txt file [duplicate]

This question already has answers here:
Writing in the beginning of a text file Java
(6 answers)
Closed 4 years ago.
I have this method that can read everything within a file but i need to be able to first add one whitespace before every new char at the beginning of everyline.
Tried to make it as easy as possible but non of it seem to work.
private static void write() throws IOException {
FileWriter fw = new FileWriter("C:\\Users\\karwa\\Desktop\\HistoryOfProgramming.txt");
for (int i = 0; i < 15; i++) {
fw.write(" ");
}
fw.close();
}
Used bufferedReader aswell that had a whileloop that was reading every line and adding one whitespace for each line but that didn't work either. Ideas?
you have to actualy read the lines and store them, only then can you add whitespace
public static void main(String... args) throws IOException {
File file = new File("test.txt");
Scanner fr = new Scanner(file);
List<String> lines = new ArrayList<>();
while (fr.hasNextLine()) {
lines.add(fr.nextLine());
}
PrintStream fw = new PrintStream(file);
for (String line : lines) {
fw.println(" " + line);
}
fr.close();
fw.close();
}
Read/write the contents to a string
Use replaceAll("\n", "\n ");

Why this code skip the first line of file? [duplicate]

This question already has answers here:
Reading UTF-8 - BOM marker
(9 answers)
Closed 5 years ago.
I applied this code more than one, this code is to read a file and for each line, it should create a new object and add it to att_agreement ArrayList, it works fine for each line except the first line, I can not find its object in the output.
Any help, please?
public ArrayList<Att_Elements> load_ann(File f) {
ArrayList<Att_Elements> att_agreement = new ArrayList<Att_Elements>();
String line="";
try {
BufferedReader read = new BufferedReader(new InputStreamReader(new FileInputStream(f), "UTF8"));
while((line = read.readLine()) != null) {
String[] SplitLine = line.split("\\|");
if (SplitLine[0].equals("Att")) {
annotation=new Att_Elements();
annotation.Type = SplitLine[0];
.
.
.
//...
att_agreement.add(annotation);
}
}
read.close();
} catch (IOException e) {
e.printStackTrace();
}
return att_agreement;
}
Here is a sample of file content (3 lines):
Your file likely has what is called a BOM located at the beginning. This is a byte order mark. Thus, your conditional .equals("Att") is not being met until the second line where the BOM is not present. A separate if statement to handle this case should work well. If you print each line read, you should see what the BufferedReader is reading as the first line. The new conditional statement can then be tailored to this value.
Another approach is to search for a generic BOM string and replace it with nothing.

If-statement checking for filename correctness (appending ".txt") not working [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 5 years ago.
So I want to accept a file name from the user. I then want to check if the last four characters of the string are ".txt". If they aren't, append ".txt" to the end of the user inputted string. If they are, skip. Simple.
But it's not working - when I enter "exampledata.txt" it still adds ".txt" and throws a FileNotFoundException - and I can't figure out why. I've taken the same calculation and printed it out/verified in debugger; my method call to substring is correct.
Relevant code:
import java.util.*;
import java.io.*;
public class MappingApp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String userInput;
System.out.print("Enter file to read from: ");
userInput = sc.nextLine();
if ( (userInput.substring(userInput.length()-4, userInput.length())) != ".txt" ) {
userInput += ".txt";
}
try {
File f = new File(userInput);
BufferedReader br = new BufferedReader(new FileReader(f));
}
catch (FileNotFoundException e) {
System.err.println(e);
}
}
}
Usually you don't compare strings as != or ==
Try changing
if ( (userInput.substring(userInput.length()-4, userInput.length())) != ".txt" )
to
if ( !(userInput.substring(userInput.length()-4, userInput.length()).equals (".txt") )
Hope this will help.

Reading text file into Java array [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
So I'm trying to take a series of "scores" from a text file to put into an array and then sort in order, rows of four, and write other methods to get the highest, lowest, average, etc. The println commands are in there but I haven't written the methods yet. I've been working all day and I'm starting to confuse myself, and now I'm getting a NullPointerException error in the main method. Any help?
package arrayops1d;
import java.io.*;
import java.util.*;
public class ArrayOps1D {
static int scores[];
public static void main(String[] args) throws Exception{
FileReader file = new FileReader("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
BufferedReader reader = new BufferedReader(file);
String scores = "";
String line = reader.readLine();
while (line != null){
scores += line;
line = reader.readLine();
}
System.out.println(scores);
System.out.println(getTotal());
System.out.println(getAverage());
System.out.println(getHighest());
System.out.println(getLowest());
System.out.println(getMedian());
System.out.println(getPosition());
System.out.println(getDeviations);
System.out.println(getStdDev);
}
Here is one way you can read the int values from a file into an array of Integer using a Scanner and a List -
Integer[] scores = null;
File file = new File("C:/Users/Steve/Documents/"
+ "NetBeansProjects/ArrayOps1D/Scores.txt");
if (file.exists() && file.canRead()) {
try {
List<Integer> al = new ArrayList<>();
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
al.add(scanner.nextInt());
} else {
System.out.println("Not an int: " + scanner.next());
}
}
scores = al.toArray(new Integer[al.size()]);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
} else {
System.out.println("Can't find file: " + file.getPath());
}
if (scores != null) {
System.out.println("Scores Read: " + Arrays.toString(scores));
}
First Issue with your code:
In your file path, Instead using / , you must use \\ or better File.separator if your program wants to be ran in different platform.
If you do not , you will have java.io.FileNotFoundException
You are reading line by line, so you can use split Function and use Integer.paraseInt or Float.parseFloat to convert each splited elements and added to your array
How to use Split in Java
How to convert String to int

NullPointerException when storing lines in an arraylist [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
I'm getting a NullPointerException in java (at this line :FileReader fstream = new FileReader(fileName)) when I try to read a text file line by line and store them in an arraylist with this code :
public ArrayList<String> StoreLineByLine(String fileName) throws IOException {
String str;
ArrayList<String> Line = new ArrayList<String>();
FileReader fstream = new FileReader(fileName);
BufferedReader myFileReader = new BufferedReader(fstream);
while ((str = myFileReader.readLine()) != null) {
Line.add(str);
}
myFileReader.close();
return Line;
}
Could anyone help me understand the problem ?
Thanks a lot !
If you're getting a NPE on that line, then fileName must be null.
BTW, if you're using JDK 8 then this may be a better way to load the lines. Replace the contents of your method with this:
return Files.readAllLines(Paths.get(fileName), Charset.defaultCharset());
...and change the method's return type from ArrayList<String> to List<String>.

Categories

Resources