String from bufferedReader to arraylist - java
I have a local server-class, which sends two String messages ("The first message", "The second message") to client-class.
In client-class I'd like to put them into an ArrayList
code from BufferedReader and then print.
void go () throws IOException {
Socket socket = new Socket("127.0.0.1",4242);
InputStreamReader streamReader = new InputStreamReader(socket.getInputStream());
BufferedReader reader = new BufferedReader(streamReader);
ArrayList <String> list = new ArrayList<String>();
while (reader.readLine() != null) {
list.add(reader.readLine());
}
System.out.println(list);
}
But all that I get - is a line "null"
What's wrong with it?
I’ll be very grateful for any help
ciprianoss is correct but also in the loop
while (reader.readLine() != null) {
list.add(reader.readLine());
}
You are reading from the file TWICE
Once in the while and the again just before you add.
list.add(reader.readLine());
as ciprianoss suggested
String line;
while( (line = reader.readLine()) != null)
{
list.add(line);
{
Once you do .readLine() it will no longer be in the buffer, change your while loop to:
String line = null;
while((line = reader.readLine()) != null) {
list.add(line);
}
Easiest way should be using bufferedReader.lines(), which returns a stream:
public List<String> readerToList(final Reader reader) {
try (final BufferedReader bufferedReader = new BufferedReader(reader)) {
return bufferedReader.lines().collect(Collectors.toList());
}
}
Related
Reading text file into arraylist
I really new to Java so I'm having some trouble figuring this out. So basically I have a text file that looks like this: 1:John:false 2:Bob:false 3:Audrey:false How can I create an ArrayList from the text file for each line?
Read from a file and add each line into arrayList. See the code for example. public static void main(String[] args) { ArrayList<String> arr = new ArrayList<String>(); try (BufferedReader br = new BufferedReader(new FileReader(<your_file_path>))) { String sCurrentLine; while ((sCurrentLine = br.readLine()) != null) { arr.add(sCurrentLine); } } catch (IOException e) { e.printStackTrace(); } }
While the answer above me works, here's another way to do it. Make sure to import java.util.Scanner. public static void main(String[] args) { ArrayList<String> list = new ArrayList<String>(); Scanner scan = new Scanner("YOURFILE.txt"); while(scan.hasNextLine()){ list.add(scan.nextLine()); } scan.close(); }
If you know how to read a file line by line, either by using Scanner or by using BufferedReader then reading a text file into ArrayList is not difficult for you. All you need to do is read each line and store that into ArrayList, as shown in following example: BufferedReader bufReader = new BufferedReader(new FileReader("file.txt")); ArrayList<String> listOfLines = new ArrayList<>); String line = bufReader.readLine(); while (line != null) { listOfLines.add(line); line = bufReader.readLine(); } bufReader.close(); Just remember to close the BufferedReader once you are done to prevent resource leak, as you don't have try-with-resource statement
This will be help to you. List<String> list = new ArrayList<String>(); BufferedReader reader = new BufferedReader(new FileReader("list.txt")); String line; while ((line = reader.readLine()) != null) { list.add(line); } reader.close(); Then you can access those elements in the arraylist.
java 8 lets you do this String fileName = "c://lines.txt"; List<String> list = new ArrayList<>(); try (Stream<String> stream = Files.lines(Paths.get(fileName))) { list = stream .map(String::toUpperCase) .collect(Collectors.toList()); } catch (IOException e) { e.printStackTrace(); } list.forEach(System.out::println);
Is this a good way of reading from a text file?
I've been looking around on the Internet trying to figure out which could be the best way to read from text files which are not very long (the use case here involves small OpenGL shaders). I ended up with this: private static String load(final String path) { String text = null; try { final FileReader fileReader = new FileReader(path); fileReader.read(CharBuffer.wrap(text)); // ... } catch(IOException e) { e.printStackTrace(); } return text; } In which cases could this chunk of code result in inefficiencies? Is that CharBuffer.wrap(text) a good thing?
If you want to read the file line by line: BufferedReader br = new BufferedReader(new FileReader(path)); try { StringBuilder sb = new StringBuilder(); String line = br.readLine(); while (line != null) { sb.append(line); sb.append(System.lineSeparator()); line = br.readLine(); } String everything = sb.toString(); } finally { br.close(); } If you want to read the complete file in one go: String text=new String(Files.readAllBytes(...)) or Files.readAllLines(...)
I would usually just roll like this. The CharBuffer.wrap(text) thing seems to only get you a single character ... File Reader docs BufferedReader br = new BufferedReader(fr); StringBuilder sb = new StringBuilder(); String s; while((s = br.readLine()) != null) { sb.append(s); } fr.close(); return sb.toString();
BufferedReader skip lines assets file java android
I'm trying to read a .txt-file that's located in my assets folder in an Android project. Search the file, read the file with the InputStreamer and the BufferedReader works just fine, but the problem is: it doesn't read ALL the lines. So when I want to add a line to an ArrayList for further use, not all the lines are present in this list. This is my code: InputStream inputStream; BufferedReader br; try { inputStream = getResources().getAssets().open("KeyMapping.txt"); br = new BufferedReader(new InputStreamReader(inputStream)); final ArrayList<String> viewList = new ArrayList<String>(); String line = null; //Add every line (except the first) to an arrayList while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char") { viewList.add(line); } br.close(); } catch (IOException e) { e.printStackTrace(); } The format of my .txt-file is like this: 1,2,3,4,5,6,7,8/char 1,,,,1,,,/a 2,,,,1,,,/b 3,,,,1,,,/c ,1,,,1,,,/d ,2,,,1,,,/e ,3,,,1,,,/f ,,1,,1,,,/g ,,2,,1,,,/h ,,3,,1,,,/i ,,,,1,,,1/j ,,,,1,,,2/k ,,,,1,,,3/l 1,,,,2,,,/m 2,,,,2,,,/n 3,,,,2,,,/o ,1,,,2,,,/p ,2,,,2,,,/q ,3,,,2,,,/r ,,1,,2,,,/s ,,2,,2,,,/t ,,3,,2,,,/u ,,,,2,,,1/v ,,,,2,,,2/w ,,,,2,,,3/x ... Only a few of these lines will be added to the ArrayList, does anyone know why?
while ((line = br.readLine()) != null && (line = br.readLine()) != "1,2,3,4,5,6,7,8,char") This line reads 2 lines from the stream, and processes the 2nd line always. Also, you cannot compare strings with != operator. Use String.equals() method. while ((line = br.readLine()) != null) { if(line.equals("1,2,3,4,5,6,7,8,char")) continue; //add if it's not that string viewList.add(line); }
Java Process can't get ErrorStream message
everyone, I have a process that needs to get standard output and log/error/exception output from the subprocess. The standard output is fine, but I can't get ErrorStream, therefore the program is stuck there because of that. Here is my simple code. There is nothing magic, but why can't I get the error stream here? Thanks for looking at it. BufferedReader standard = new BufferedReader(new InputStreamReader(process.getInputStream())); BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); String line = null; while ((line = standard.readLine()) != null) { System.out.println(line); } while ((line = error.readLine()) != null) { System.out.println(line); } Now, as suggested, i used two threads to process the output and error streams, but still had the same problem, as follows. Can anybody give me some insights? Thanks. ProcessBuilder pb = new ProcessBuilder(listArgs); pb.redirectErrorStream(); Process process = pb.start(); StreamThread output = new StreamThread(process.getInputStream()); StreamThread error = new StreamThread(process.getErrorStream()); output.start(); error.start(); while (true) { try { output.join(); break; } catch (InterruptedException ie) { ie.printStackTrace(); } } The definition of the StreamThread: public static class StreamThread extends Thread{ private InputStream input = null; public StreamThread(InputStream in){ input = in; } String line = null; public void start(){ BufferedReader reader = new BufferedReader(new InputStreamReader(input)); try{ while( (line=reader.readLine()) != null ){ System.out.println(line); } reader.close(); }catch (IOException e){ e.printStackTrace(); } } }
Look at your loops: while ((line = standard.readLine()) != null) { System.out.println(line); } while ((line = error.readLine()) != null) { System.out.println(line); } You're going to keep reading from the output stream until it's finished - which is likely to be when the process terminates. Only then do you start reading the error stream. You should probably put at least one of these into a different thread, so you can read from both streams at the same time.
How to escape a line that starts with a special character while reading files in java
Suppose a file contains the following lines: #Do #not #use #these #lines. Use these. My aim is to read only those lines which does not start with #. How this can be optimally done in Java?
Let's assume that you want to accumulate the lines (of course you can do everything with each line). String filePath = "somePath\\lines.txt"; // Lines accumulator. ArrayList<String> filteredLines = new ArrayList<String>(); BufferedReader bufferedReader = null; try { bufferedReader = new BufferedReader(new FileReader(filePath)); String line; while ((line = bufferedReader.readLine()) != null) { // Line filtering. Please note that empty lines // will match this criteria! if (!line.startsWith("#")) { filteredLines.add(line); } } } finally { if (bufferedReader != null) bufferedReader.close(); } Using Java 7 try-with-resources statement: String filePath = "somePath\\lines.txt"; ArrayList<String> filteredLines = new ArrayList<String>(); try (Reader reader = new FileReader(filePath); BufferedReader bufferedReader = new BufferedReader(reader)) { String line; while ((line = bufferedReader.readLine()) != null) { if (!line.startsWith("#")) filteredLines.add(line); } }
Use the String.startsWith() method. in your case you would use if(!myString.startsWith("#")) { //some code here }
BufferedReader.readLine() return a String. you could check if that line starts with # using string.startsWith() FileReader reader = new FileReader("file1.txt"); BufferedReader br = new BufferedReader(reader); String line=""; while((line=br.readLine())!=null){ if(!line.startsWith("#")){ System.out.println(line); } } }