I'm trying to write a program, which reads text from a file that is specified by the user. Now, this program should detect an empty line.
This is what I have unsuccessfully tried:
public static void editFile(String filePath) throws FileNotFoundException, IOException {
file = new File(filePath);
if(file.exists()) {
fileRead = new FileReader(file);
bufferedReader = new BufferedReader(fileRead);
String line = bufferedReader.readLine();
System.out.println(line);
while(line != null) {
line = bufferedReader.readLine();
if(line == "") {
//line = null;
System.out.println("a");
}
System.out.println(line);
}
}
}
To be more clear:
If I'm passing in a text file with for example this text:
test1
test2
test3
test4
it should print 2 a's in the console because of the empty spaces, but it doesn't.
Thank you for your time, I am glad for any suggestion you may have.
This is because the comparison is wrong. You can't use == to compare two strings, you need to use the equals method:
if(line.equals(""))
Since you are checking for empty string, you can also write
if(line.isEmpty())
How do I compare strings in java?
BackSlash is entirely correct, and has answered your question. I'd like to add that your code has some errors:
You're not closing the Reader
You're not testing the first line for blank
You're processing the null value when reaching EOF
The following corrects these errors.
public static void editFile(String filePath) throws IOException
{
File file = new File(filePath);
if (file.exists())
{
BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
try
{
String line;
while ((line = bufferedReader.readLine()) != null)
{
if (line.isEmpty())
{
//line = null;
System.out.println("a");
}
System.out.println(line);
}
} finally {
bufferedReader.close();
}
}
}
Output is:
test1
test2
a
test3
a
test4
Note: You're still printing the blank line in addition to the "a".
What you're doing wrong is that you're comparing the variable itself, not its value with a null string.
Generally there are built-in functions in the string class that return true & false for checking if it's == with something.
if(line.equals("")) { ... }
Or you can just use any alternative way.
Related
Problem: I can't parse my file test.txt, by spaces. I can 1) read text files, and I can 2) parse strings, but I cannot connect the two and parse a text file! My purpose is to learn how to analyze text files. This is a simplified approach to that.
Progress: Thus far, I can read test.txt using FileReader and BufferedReader, and print it to console. Further, I can parse simple String variables. The individual operations run, but I'm struggling with parsing an actual text file. I believe this is because my test.txt is stored in the buffer, and after I .close() it, I can't print it.
Text File Content:
This is a
text file created, only
for testing purposes.
Code:
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.print(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
// readFileMethod a = new readFileMethod(line);
System.out.println(a.splitIt());
}
}
Preemptive thank you for your sharing your knowledge. Many posts on reading and parsing have been solved here on SO, but I've not the understanding to implement others' solutions. Please excuse me, I've only been learning Java a few months and still struggle with the basics.
Ok lets make the splitting into a mthod
private static void splitIt (String toTest) {
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece.
System.out.println(piece);
}
}
then you can call it from within
while((line = reader.readLine()) != null)
{
System.out.println(line);
splitIt (line);
}
Building on Scary Wombat and your code, i made some changes.
It should now print the Line that is being read in and each word that is separated by space.
import java.io.*;
public class ReadFile {
//create method to split text file, call this from main
public static void splitIt(String toTest)
{
String[] result = toTest.split(" ");
for (String piece:result)
{
//loop through the array and print each piece
System.out.println(piece);
}
}
public static void main(String[] args) {
//create readfile method
try
{
File test = new File("C:\\final\\test.txt");
FileReader fileReader = new FileReader(test);
BufferedReader reader = new BufferedReader(fileReader);
String line = null;
//While there are still lines to be read, read and print them
while((line = reader.readLine()) != null)
{
System.out.println(line); // print the current line
splitIt(line);
}
reader.close();
}
//Catch those errors!
catch (Exception ex)
{
ex.printStackTrace();
}
}
}
Hi I was looking to get some help with skipping null lines, I've searched for answers but im not able to find any. This is the code I'm trying to use:
BufferedReader in = new BufferedReader(new FileReader(newest));
String line = "";
while (true) {
if ((line = in.readLine()) == null) {
I would expect the code to look something like this:
String line;
while ((line=in.readLine())!=null) {
if (!line.isEmpty()) {
// do stuff
}
}
Normally I'd trim each line before checking if it is empty, but you say you want to exclude "a line that is blank and has no spaces", which implies you want to include lines that are just space.
If you do want to skip lines that are all whitespace, you could do this:
String line;
while ((line=in.readLine())!=null) {
if (!line.trim().isEmpty()) {
// do stuff
}
}
The point of the while condition is that the BufferedReader will return null when the input is finished, so that should trigger the end of the loop.
Lines won't be null, they may just be empty. What I would do is check if it is empty:
if ((line = in.readLine()) != null) {
line = line.trim();
if (line.isEmpty()) {
}
}
While reading from this stream, null will only be encountered at the end of the stream (file in this case). If you're looking for an empty/blank string, that test is within the loop (below).
Note that String.trim() does not trim the object itself, it returns the trimmed String. Equals method should generally be used to test for Object (such as String) equality.
BufferedReader in = new BufferedReader(new FileReader(newest));
String line = "";
//Line below keeps looping while the reader return a valid line of text.
//If the end of stream (file in this case) has been reached, you'll get null.
while ((line=in.readLine())!=null) {
//line below tests for empty line
if(line.trim().equals(""){
}
}
I am trying to write a java program to parse relevant strings from a .txt file with a certain format.
I want to use the contents of the .txt file to initiate data for my classes. A sample file would look like this:
Movies
Lord of the Rings: 180
Fight Club: 120
...
Theaters
A:100
B:50
C:200
...
Shows
1,1,960
1,1,1080
1,1,1200
1,3,1020
1,3,1140
2,2,990
2,2,1210
...
Prices
Adult:10
Child:7
Senior:8
...
End
This is what I have so far (and it is returning an error when trying to read the above file to initialize my class.
public static void inititializeFromFile(String fileName) throws IOException {
BufferedReader reader = new BufferedReader(new FileReader(fileName));
String line;
while((line = reader.readLine()) != null) {
if(line.equals("Movies")) {
while (!(line.equals("Theaters"))) {
String currentline = line;
String[] parts = currentline.split(":");
String part1 = parts[0];
String part2 = parts[1];
movies.add(new Movie(part1, part2));
}
}
// do basic string comparisons here
if(line.equals("...")) {
// do something
}
else if(line.contains(":")) {
// most likely of type A:100, B:50
}
else if(line.equals("End")) {
// do something
}
else {
// anything else
}
}
reader.close();
}
}
Here is a sample program that will read in the file for you, line by line, and has some scenarios to determine what type of line we are looking at. I was lazy and threw the IOExceptions that might be thrown at me in the code - you should never do this, instead modify the program to use a try catch.
import java.io.*;
public class tmp {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
String line;
while((line = br.readLine()) != null) {
// do basic string comparisons here
if(line.equals("...")) {
// do something
}
else if(line.contains(":")) {
// most likely of type A:100, B:50
}
else if(line.equals("End")) {
// do something
}
else {
// anything else
}
}
br.close();
}
}
If I have something like this in my code:
String line = r.readLine(); //Where r is a bufferedReader
How can I avoid a crash if the next line is the end of the file? (i.e. null)
I need to read the next line because there may be something there that I need to deal with but if there isn't the code just crashes.
If there is something there then all is OK, but I can't be guaranteed that there will be something there.
So if I do something like: (pseudo code):
if (r.readLine is null)
//End code
else {check line again and excecute code depending on what the next line is}
The issue I have with something like this is, that when I check the line against null, it already moves onto the next line, so how can I check it again?
I've not worked out a way to do this - any suggestions would be a great help.
Am... You can simply use such a construction:
String line;
while ((line = r.readLine()) != null) {
// do your stuff...
}
If you want loop through all lines use that:
while((line=br.readLine())!=null){
System.out.println(line);
}
br.close();
You can use the following to check for the end of file.
public bool isEOF(BufferedReader br)
{
boolean result;
try
{
result = br.ready();
}
catch (IOException e)
{
System.err.println(e);
}
return result;
}
In your case you can read the next line because there may be something there.If there isn't anything, your code won't crash.
String line = r.readLine();
while(line!=null){
System.out.println(line);
line = r.readLine();
}
A question in the first place, why don't you use "Functional Programming Approach"? Anyways, A new method lines() has been added since Java 1.8, it lets BufferedReader returns content as Stream. It gets all the lines from the file as a stream, then you can sort the string based on your logic and then collect the same in a list/set and write to the output file. If you use the same approach, there is no need to get worried about NullPointerException. Below is the code snippet for the same:-
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
public class LineOperation {
public static void main(String[] args) throws IOException {
Files.newBufferedReader(Paths.get("C://xyz.txt")).
lines().
collect(Collectors.toSet()). // You can also use list or any other Collection
forEach(System.out::println);
}
}
You can do it via BufferReader. I know this is not relevant to following question. But I would post it for extra fact for a newbie who would not use BufferReader but Scanner for reading file.
A part from BufferReader you could use Java Scanner class to read the file and check the last line.
Buffer Reader
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line
}
}
Scanner
try {
Scanner scanner = new Scanner(new FileReader(file));
while (scanner.hasNext()) {
// Above checks whether it has or not ....
}
} catch (IOException e) {
e.printStackTrace();
}
If you use this code fragment in a multi threaded environment, go ahead with BufferReader since its synchronized.
In addition, BufferReader is faster than Scanner.
If you would like to do some check like:
if (reader.ready())
stringBuilder.append("#");
You can use ready()
public static void check() throws IOException {
InputStream in = new FileInputStream(new File(filePath));
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
if (reader.ready())
stringBuilder.append("#");
}
String returnedString = stringBuilder.toString();
System.out.println(returnedString);
}
You could purposely have it throw the error inside your loop. i.e.:
String s = "";
while (true) {
try {
s = r.readline();
}catch(NullPointerException e) {
r.close();
break;
}
//Do stuff with line
}
what everyone else has sad should also work.
I need to copy a line from a file to another depending on condition
this is my code
import org.apache.commons.io.FileUtils;
public class FileCopy {
public static void main(String args[]) throws IOException {
File source = \\
File fileToCopyFrom \\
File target :\\
if (!target.exists()) {
target.createNewFile();
}
PrintStream fstream =new PrintStream(target);
BufferedReader brSource = new BufferedReader(new FileReader(source));
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
String lineSource;
String lineToCopy;
while((lineSource = brSource.readLine()) != null) {
while ((lineToCopy=brFileToCopyFrom.readLine())!=null) {
if (lineToCopy.contains(lineSource.substring(lineSource.indexOf("_")+1, lineSource.indexOf(".")-1)))
fstream.println(lineToCopy);
}
}
}}
but it copy only the first line
where is the error?
Only the first is copied because in the second iteration of the first while the brFileToCopyFrom is reached the end of file.
You need to open the BufferedReader brFileToCopy inside the first while (example 1) or use a mark/reset feature (example 2).
Example 1:
while ((lineSource = brSource.readLine()) != null) {
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
...
}
}
}
Example 2:
brFileToCopyFrom.mark(1024); // number of characters to be read while preserving the mark
while ((lineSource = brSource.readLine()) != null) {
brFileToCopyFrom.reset();
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
...
}
}
}
I suggest to use commons-io.jar. In this FileUtils class lot of methods to do File operation like copy, move and remove.
EDIT
try with below if conndition which contains break.
while ((lineSource = brSource.readLine()) != null) {
while ((lineToCopy = brFileToCopyFrom.readLine()) != null) {
if (lineToCopy.contains(lineSource.substring(
lineSource.indexOf("_") + 1,
lineSource.indexOf(".") - 1))) {
fstream.println(lineToCopy);
break;
}
}
}
you create your stream, you read all enntries from your stream, for first line, but when you want to do this for second line brFileToCopyFrom is empty (you already took everything from it when you were checking your first line.
so what you could do is move creating your brFileToCopyFrom to the loop,
while((lineSource = brSource.readLine()) != null) {
BufferedReader brFileToCopyFrom = new BufferedReader(new FileReader(fileToCopyFrom));
...
that should works