Creating file and writing to it (null pointer) - java

I want to create a method that reads from a file, then creates a file which will then write a certain subset of what was read from but I keep getting a null pointer exception at output.write(line) and I am not sure why?
public void readCreateThenWriteTo(String file, String startRowCount, String totalRowCount) {
BufferedReader br = null;
File newFile = null;
BufferedWriter output = null;
StringBuilder sb = null;
int startRowCountInt = Integer.parseInt(startRowCount);
int totalRowCountInt = Integer.parseInt(totalRowCount);
try {
br = new BufferedReader(new FileReader(file));
sb = new StringBuilder();
newFile = new File("hiya.txt");
output = new BufferedWriter(new FileWriter(newFile));
String line = "";
int counter = 0;
while (line != null) {
line = br.readLine();
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("File was not found.");
e.printStackTrace();
} finally {
// Should update to Java 7 in order to use try with resources and then this whole finally block can be removed.
try {
if ( br != null ) {
br.close();
}
if ( output != null ) {
output.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
LOGGER.info("Couldn't close BufferReader.");
e.printStackTrace();
}
}
}

You need to check the result of readLine() before you enter the loop:
while ((line = br.readLine()) != null) {
if (startRowCountInt <= counter && counter <= totalRowCountInt) {
System.out.println(line);
output.write(line);
}
counter++;
}

Related

Reading MultipartFile and being able to break out of loop

I have looked at two different ways of reading MultipartFile.
Using the forEach method works, but I can not break out of the forEach loop. I understand I can throw exceptions in the forEach loop to exit the loop but from what I have read it is not good practice.
private boolean validateFile(MultipartFile idFile) {
AtomicBoolean validated = new AtomicBoolean(true);
try {
InputStream inputStream = idFile.getInputStream();
new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.forEach(
line -> {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated.set(false);
}
}
);
} catch (Exception ex) {
validated.set(false);
}
return validated.get();
}
The problem with using forEach is that I can not break out of the loop after executing validated.set(false)
I have also tried using the method below in order to use breaks
private boolean validateFile(MultipartFile idFile) {
boolean validated = true;
InputStream inputStream = null;
BufferedReader br = null;
try {
inputStream = idFile.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8));
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated = false;
break;
}
}
} catch (Exception e) {
validated = false;
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
return validated;
}
The problem I am facing with the method above is that throw new RuntimeException(e); in the finally block causing sonar errors.
How can I read MultipartFile and being able to break out of the loop? I also don't want to use throws in the finally block since it causes sonar errors.
For your stream-based solution, you can use Stream.noneMatch(). On the first element, which matches the predicate it will stop evaluating the rest of the elements in the stream and return false.
private boolean validateFile(MultipartFile idFile) {
try {
InputStream inputStream = idFile.getInputStream();
return new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))
.lines()
.noneMatch(line -> line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$"));
} catch (Exception ex) {
return false;
}
}
For the loop based solution, you can use try-with-resouces statement. It will automatically close the resources for you, so you don't need to do it manually.
private boolean validateFile(MultipartFile idFile) {
boolean validated = true;
try (InputStream inputStream = idFile.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) {
line = line.trim();
if (line.length() != 3 || !line.matches("^[a-zA-Z0-9]*$")) {
validated = false;
break;
}
}
} catch (IOException exc) {
return false;
}
return validated;
}
You could try to use .takeWhile in order to find the first not matching element. It will break the loop in the first occurrence of not matching element and returns the elements until that element.

How to solve infinite readLine while

I have a program and one of the methods I use is for counting the lines a .txt file has and return an integer value. The problem is when I execute it, despite I wrote if my line is == null the while has to stop, the while loop keeps going, ignoring the nulls it gets infinitely.
I don't know what to do to try to solve it.
private int sizeOfFile (File txt) {
FileReader input = null;
BufferedReader count = null;
int result = 0;
try {
input = new FileReader(txt);
count = new BufferedReader(input);
while(count != null){
String line = count.readLine();
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
input.close();
count.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
It has to stop when it detects a null, which means there are no more lines, but it keeps going.
When you instantiate a BuffereReader assign it to count, count will always be non-null and hence will satisfy the while loop:
count = new BufferedReader(input); //count is holding an instance of BufferedReader.
while(count != null){ //here count is non-null and while loop is infinite and program never exits.
Instead use the following code, where the each line will be read and checked whether it is null, if null then the program will exit.:
input = new FileReader(txt);
count = new BufferedReader(input);
String line = null;
while(( line = count.readLine())!= null){ //each line is read and assigned to the String line variable.
System.out.println(line);
result++;
}
If you are using JDK-1.8 you can shorten your code using the Files API:
int result = 0;
try (Stream<String> stream = Files.lines(Paths.get(txt.getAbsolutePath()))) {
//either print the lines or take the count.
//stream.forEach(System.out::println);
result = (int)stream.count();
} catch (IOException e) {
e.printStackTrace();
}
count is your BufferedReader, your loop should be on line! Like,
String line = "";
while (line != null) {
line = count.readLine();
Also, you should use try-with-Resources to close your resources (instead of the finally block). And you could write that while loop more idiomatically. Like,
private int sizeOfFile(File txt) {
int result = 0;
try (BufferedReader count = new BufferedReader(new FileReader(txt))) {
String line;
while ((line = count.readLine()) != null) {
System.out.println(line);
result++;
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
return result;
}

How can I change this to just array?

I have written this code but I have to change this from saving in list to saving in array. So that every animal in my txt file should have its position in the array. There is 10 animals. Anyone can help?
public class Main {
public static void main(String[] args) {
String line = "";
int count = 0;
List<String> arrayList = new ArrayList<>();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
while (line != null) {
count++;
line = br.readLine();
if (line == null)
break;
if (count == 3 || count % 3 == 1 && !line.equals("1") &&
!line.equals("5") && !line.equals("10"));
arrayList.add(line);
}
System.out.println(Arrays.toString(arrayList.toArray()));
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}catch (IOException e) {
System.err.println("Cannot read this file.");
}
}
}
With Java8+, you could do :
Path path = Paths.get("Zoo.txt");
String[] animals = Files.lines(path, Charset.defaultCharset()).toArray(String[]::new);
Based on #Ryan suggestion :
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "";
int count = 0;
int countLineNumber=0; //to count line numbers
List<String> arrayList = new ArrayList();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
while (line != null) {
count++;
line = br.readLine();
if (line == null)
break;
if (count == 3 || count % 3 == 1 && !line.equals("1") &&
!line.equals("5") && !line.equals("10"));
arrayList.add(line);
countLineNumber++;
}
//System.out.println(countLineNumber);
br.close();
} catch (FileNotFoundException e) {
System.err.println("File not found.");
}catch (IOException e) {
System.err.println("Cannot read this file.");
}
//getting elements from arayList saving them into a array
String[] array=new String[countLineNumber];
for(int i=0;i<countLineNumber;i++){
array[i]=arrayList.get(i);
}
//display element in array
for(int k=0;k<array.length;k++){
System.out.println(array[k]);
}
}

Reading and writing arraylist to textfile

I'm having a problem with reading and writing arraylist to a text file. Specifically with reading. What I'm trying to do is read from a text file and transfer it to an array list. After which i would edit the list and write it back to the text file. I think I go the writing done but not the reading. I've tried reading several similar questions here but cant seem to inject it into my code.
Reading code
public void read(List<AddressBook> addToList){
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
} }
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
Here's what I've done with the write
public void write(List<AddressBook> addToList) {
try {
File file = new File("bank_account.csv"); //file
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
//FileWriter fw = new FileWriter(file.getAbsoluteFile());
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);
BufferedWriter bw = new BufferedWriter(fw);
for (AddressBook write : addToList) {
bw.write(write.getName() + "," + write.getAddress() + "," + write.getTelNum() + "," + write.getEmailAdd());
bw.newLine();
}
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
for (AddressBook read : addToList) {
br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
}
}
I bet in there you will need to do something like:
reading each line
parsing it (each line is a CSV)
creating a new AddressBook object with all that info
add it to the collection
The code for that will look like:
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
String[] splitted = currentLine.split(",");
AddressBook address = new AddressBook(splitted[0], splitted[1], splitted[2], splitted[3]);
addToList.add(address);
}
Of course there are things you will need to check and validate, but that is roughtly it.
Maybe you need read method like this.
public void read() {
List<AddressBook> addToList =new ArrayList<AddressBook>();
BufferedReader br = null;
try {
String currentLine= "";
br = new BufferedReader(new FileReader("bank_account.csv"));//file na gusto mo basahin
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine); // print per line
// for (AddressBook read : addToList) {
String[] split =currentLine.split(",");
AddressBook read = new AddressBook();
read.setName(split[0]);
read.setAddress(split[1]);
read.setTelNum(split[2]);
read.setEmailAdd(split[3]);
// br.read(read.getName() + read.getAddress() + read.getTelNum() + read.getEmailAdd());
addToList.add(read);
// }
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)
{
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

delete text file java doesn't work

Here's example:
public static void main (String[] args){
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
String temppath = "C:\\Users\\Charbel\\Desktop\\temp.txt";
File file = new File(path);
File tempfile = new File(temppath);
int numl = search("x");
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
BufferedWriter bw = new BufferedWriter(new FileWriter(temppath));
while (( line = bf.readLine()) != null)
{
if(countL != numl){
bw.write(line);
bw.newLine();
}
countL++;
}
bf.close();
bw.close();
file.delete();
boolean successful = tempfile.renameTo(file);
System.out.println(successful);
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
}
public static int search(String name)
{
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
try {
BufferedReader bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
bf.close();
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
return -1;
}
}
Hello there .. i am trying to read the line of a specific string in a text file , get the number of its line , then copy all the data in the file to another text file except the line of the string
the code is sometimes working 100% and sometimes no ; I go to my desktop I see both files the temp and the original one without deleting and renaming it
i think i have a problem in deleting the file what do you think coders ?
Because when the search method find name(actually "x"),don't reach the line bf.close(), so bf is still opened and file.delete() fails.
So, you need to modify the search method to the below:
public static int search(String name) {
String path = "C:\\Users\\Charbel\\Desktop\\Dictionary.txt";
int countL = 0;
String line;
BufferedReader bf = null;
try {
bf = new BufferedReader(new FileReader(path));
while (( line = bf.readLine()) != null)
{
int indexfound = line.indexOf(name);
if (indexfound == 0) {
return countL;
}
countL++;
}
}
catch (IOException e) {
System.out.println("IO Error Occurred: " + e.toString());
}
finally {
if(bf != null) {
try {
bf.close();
}
catch(IOException ignored) {}
}
}
return -1;
}

Categories

Resources