Buffered Reader is not reading my whole file java - java

BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\NormenYu\\Desktop\\Programming\\Java\\eclipse\\Book\\"+thebook+".txt"));
String line = reader.readLine();System.out.println(line);
My File:
(tab)You are on a hiking trip with your friend(also lives with you in a rented apartment). You suddenly find yourself walking into a jungle. As you walk, you suddenly find yourself very lonely. “Help!”, you heard.
(enter)(tab)“What was that,” you ask your friend. There is no reply. Wait... where is your friend? You start to find your way back, and suddenly you find your friend stuck in quicksand.
Do you: Walk towards your friend and try to save him or Stay away because you might also get stuck in quicksand
The program prints: You are on a hiking trip with your friend(also lives with you in a rented apartment). You suddenly find yourself walking into a jungle. As you walk, you suddenly find yourself very lonely. “Help!”, you heard.
HELP!! By the way, the things in parentheses are not written in the notepad.

Using a loop you can read each line in the file.
BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\NormenYu\\Desktop\\Programming\\Java\\eclipse\\Book\\"+thebook+".txt"));
String line;
while((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close()

You are only reading in one line with the method readLine. You need to loop over the file until you reach the end. Something like this:
BufferedReader in = new BufferedReader(new FileReader(file));
while (in.ready()) {
String s = in.readLine();
System.out.println(s);
}
in.close();

BufferedReader reader = new BufferedReader(new FileReader("C:\\Users\\NormenYu\\Desktop\\Programming\\Java\\eclipse\\Book\\"+thebook+".txt"));
String full = "";
String line;
while ((line = reader .readLine()) != null) {
full += line;
}
// full now contains the whole content of your file.

Related

How to store different parts of a text file into different variables?

I am trying to read parts of a text file with the format
John Smith
72
160
The first line being the name (string), and the second and third lines being height and weight (both ints). However, I cannot find a way to store each of these into their own variables, instead I can only figure out how to store the whole thing into one variable and print it. This is the code that I have as of now
try
{
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println(stringBuffer);
}
In this part
stringBuffer.append(line);
stringBuffer.append("\n");
I was thinking of trying to add a part in the middle of both those lines that stored a variable, but it did not seem possible. I also thought of using a for loop and using that to my advantage somehow, but could not figure out a way to do it with that either.
Is there any possible way to do this that I do not know about? Thank you
Reading and parsing a text file in Java has been getting easier in every new version. You can try the following way:
List<String> lines = Files.lines(Paths.get("person.txt")).collect(Collectors.toList());
String name = lines.get(0);
Integer height = Integer.parseInt(lines.get(1));
Integer weight = Integer.parseInt(lines.get(2));
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String firstline = bufferedReader.readLine();
String secondline = bufferedReader.readLine();
String thirdline = bufferedReader.readLine();
fileReader.close();

use bufferedreader on a txt file twice?

i have to count the lines on a file but later in the code I also have to print what's in that file, but I can't use the reader twice it just says null. How can I work this out without creating a bunch of bufferedreader objects?
thanks
Print and count at the same time?
Move the lines to an array then print them?
Make sure you've closed the file before reopening again?
Try closing the buffer, and then re-opening it again.
BufferedReader bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
String line = bufferedReader.readLine();
int lineCount = 0;
while(line != null){
lineCount += 1;
line = bufferedReader.readLine();
}
System.out.println("Line count is: " + lineCount);
bufferedReader.close();
bufferedReader = new BufferedReader(new FileReader("src/main/java/com/william/sandbox/stackoverflow/samples20160306/Demo.java"));
line = bufferedReader.readLine();
while(line != null){
System.out.println(line);
line = bufferedReader.readLine();
}
}
You can use BufferedReader's mark() and reset() methods to jump back to a specific position.
try (BufferedReader r = new BufferedReader(new FileReader("somefile.txt"))) {
// marks this position for the next 10 characters read
// after that the mark is lost
r.mark(10);
// do some reading
// jump back to the mark
r.reset();
}
Note that, BufferedReader supports marking but not all Readers do. You can use markSupported() to check.

Java Outprinting Large File Line By Line

Every time I do something like
BufferedReader br = new BufferedReader(new FileReader(f));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
br.close();
It won't outprint line by line. Instead it will lag for 2-3 seconds then show it all at once. I've tried putting sleep methods etc. How can I make it so it takes its time and goes through each one rather than just lagging and spitting it all out at once?
Try flushing the output.
System.out.flush();
After each System.out.println
This is probably because your file doesn't have carriage return characters at the end of each line. So, it's considering the entire file as one line.
Try sending the lines to an array list. See if the arraylist contains each line. Then try iterating the array list to the website chunk by chunk.
BufferedReader br = new BufferedReader(new FileReader(f));
ArrayList<String> list = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
list.add(line);
}
br.close();
for(String one_line: list){
//send lines to website:
//sendLine(one_line);
}

Issues in getting the output when calling a python script from Java

I've a Java program to call a python script. I've used exec method. Please find the code snippet below:
Python program (which is to gather a portion of text from wikipedia), when run separately, gives me proper output. When called from Java, I'm not getting the complete output from python program.
I checked the status of BufferedReader Object using ready() method ( as explained here, and the code entered into infinite loop.
I think others also have faced similar problems-https://stackoverflow.com/a/20661352/3409074
Can anyone help me?
public String enhanceData(String name,String entity) {
String s = null;
StringBuffer output = new StringBuffer();
try{
String command="python C://enhancer.py "+name+" "+entity;
Process p = Runtime.getRuntime().exec(command);
BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream()));
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
output.append(s);
}
The while loop condition has actually already read a line so you are double reading it for every time in the loop.
while ((s = stdInput.readLine()) != null) {
//s=stdInput.readLine(); <- don't need this
System.out.println(s);
output.append(s);
}
/Nick

Reading group of lines in HUGE files

I have no idea how to do the following: I want to process a really huge textfile (almost 5 gigabytes). Since I cannot copy the file into temporarily memory, I thought of reading the first 500 lines (or as many as fit into the memory, I am not sure about that yet), do something with them, then go on to the next 500 until I am done with the whole file.
Could you post an example of the "loop" or command that you need for that? Because all the ways I tried resulted in starting from the beginning again but I want to go on after finishing the previous 500 lines.
Help appreciated.
BufferedReader br = new BufferedReader(new FileReader(file));
String line = null;
ArrayList<String> allLines = new ArrayList<String>();
while((line = br.readLine()) != null) {
allLines.add(line);
if (allLines.size() > 500) {
processLines(allLines);
allLines.clear();
}
}
processLines(allLines);
Ok so you indicated in a comment above that you only want to keep certain lines, writing them to a new file based on certain logic. You can read in one line at a time, decide whether to keep it and if so write it to the new file. This approach will use very little memory since you are only holding one line at a time in memory. Here is one way to do that:
BufferedReader br = new BufferedReader(new FileReader(file));
String lineRead = null;
FileWriter fw = new FileWriter(new File("newfile.txt"), false);
while((lineRead = br.readLine()) != null)
{
if (true) // put your test conditions here
{
fw.write(lineRead);
fw.flush();
}
}
fw.close();
br.close();

Categories

Resources