NullPointerException Error in program that writes to file - java

I am trying to print strings into a file. What have I done wrong and it always gives me a NullPointException? I believe my exceptions catch something or an argument is needed and I dont enter it. But where?
I have writen this code, that contains the main function.
EDIT: Getting error in the second line from the bottom some.items[0]="Testing One!";.
import java.io.*;
public class StringPrinter {
public String[] items;
public File file;
public StringPrinter(String fileName){
file = new File(fileName);}
public void toFile(){
try{
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st:items){
pw.println(st);
}
}
catch(Exception exception){}
}
public static void main(String args[]){
StringPrinter some=new StringPrinter("Workyou.txt");
some.items[0]="Testing One!";
some.items[1]="Testing Two!";
some.toFile();
}
}

It seems you are getting Exception here
some.items[0]="Testing One!";
this is because you did not initialize
public String[] items;
initialize it something like this in your constructor
public StringPrinter(String fileName){
file = new File(fileName);
items = new String[SIZE];
}

first : As all said you have to initialize the array.
Second : Why not print data to file
Solution :
In method ToFile()
after the for loop printing the string[] value, you need to close the Printer Writer
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st:items){
pw.println(st);
}
**pw.close()**
It will print your data to file.

You're trying to set the string Testing One! to the first position of the array items, but you did not initialize that string array
some.items[0]="Testing One!";
If you change this line.
public String[] items;
to this one
public String[] items = new String[2];
then it will work. Notice that you must predefine the size of the array. Notice that the array size is fixed. If you don't want the array size to be fixed, I suggest you use the wrapper class ArrayList, which size can be expanded.
import java.io.*;
import java.util.ArrayList;
public class StringPrinter {
public ArrayList<String> items = new ArrayList<String>();
public File file;
public StringPrinter(String filename) {
file = new File(filename);
}
public void toFile() {
try {
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st : items) {
pw.println(st);
}
pw.close();
}
catch(Exception exception) { }
}
public static void main(String args[]) {
StringPrinter some = new StringPrinter("Workyou.txt");
some.items.add("Testing One!");
some.items.add("Testing Two!");
some.toFile();
}
}

The items array is not initialized. You got to initialize it before actually assigning some values. If you do not want to create a fixed size classical array then you can try to use ArrayList.

Try this, the complete solved code:
import java.io.*;
public class StringPrinter {
public String[] items;
public File file;
public StringPrinter(String filename) {
file = new File(filename);
}
public void toFile() {
try {
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st : items){
pw.println(st);
}
pw.close(); //needed to close the writer stream to write data in file
}
catch(Exception exception) {}
}
public static void main(String args[]) {
StringPrinter some = new StringPrinter("Workyou.txt");
some.items = new String[2]; //needed to initialize array with size
some.items[0]="Testing One!";
some.items[1]="Testing Two!";
some.toFile();
}
}

Try with this , this should print the text in a file
public class StringPrinter {
public String[] items = new String [2];
public File file;
public StringPrinter(String fileName){
file = new File(fileName);}
public void toFile(){
try{
PrintWriter pw = new PrintWriter(new FileWriter(file, false));
for (String st:items){
pw.print(st);
pw.flush();
}
}
catch(Exception exception){}
}
public static void main(String args[]){
StringPrinter some=new StringPrinter("Workyou.txt");
some.items[0]="Testing One!";
some.items[1]="Testing Two!";
some.toFile();
}
}
Documentation for flush . Not required to close the writers compulsorily to see the content in a file , just calling the flush to the writer it will add the content to the files.

Related

While using a boolean method, how do I add the String contents of a txt file into an array list

I am attempting to use the method "public boolean readArtists" with a scanner to read strings from a file and return true if opened successfully. This method is also supposed to "Adds to the list all of the artists stored in the file passed parameter."
I've seen how to write the code in a public static void method that will read the text file and return it:
public static void main(String[] args) {
File file = new File("artists30.txt");
String content = null;
try {
try (Scanner scanner = new Scanner(file, StandardCharsets.UTF_8.name())) {
content = scanner.useDelimiter("\\A").next();
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(content);
}
Here is the test:
I have to keep the method "public boolean readArtists(String filename), so my question is, within this method, how do I read the contents of the text file into an ArrayList using a scanner, while also returning true if the file is opened successfully, Otherwise, handling the exception, displaying an appropriate error message containing the name of the missing file and return false.
public class Artists{
public static ArrayList<String> artists = new ArrayList<String>();
public static void main(String[] args) {
System.out.println(readArtists("filename goes here"));
System.out.println(artists);
}
public Artists(String artist, String genre)
{
}
public static boolean readArtists(String fileName) {
Scanner sc = null;
try {
File file = new File(fileName);
if(file.createNewFile()) {
System.out.println("err "+fileName);
return false;
}
sc = new Scanner(file);
while(sc.hasNextLine()) {
artists.add(sc.nextLine());
}
}catch(Exception e) {
e.printStackTrace();
}
if(sc!=null) {sc.close();}
return true;
}
}
This answer reads data from a .txt document into an ArrayList, as long as the .txt document names are on seperate lines in the document. It also outputs err \FILE\NAME and returns false if the document does not exist and true if it does. https://www.w3schools.com/java/java_files.asp is a great website to learn java by the way and this link brings you to the file handling page.
You can achieve that using,
public static void main(String[] args) throws FileNotFoundException {
String filepath = "C:\\Users\\Admin\\Downloads\\testFile.txt";
List<String> arrayList = new ArrayList<>();
if(readArtists(filepath)) {
Scanner sc = new Scanner(new File(filepath));
sc.useDelimiter("\\A");
while(sc.hasNext()) {
arrayList.add(sc.next());
}
}
System.out.println(arrayList);
}
public static boolean readArtists(String filename)
{
File file = new File(filename); //full path of the file with name
return file.canRead();
}

How to read from textfile and pass values to another class Java?

I'm making a Java program that needs to read info from a text file and then store it in an array and pass it to another class when called. My issue is that I can't seem to call it due to the IOException needed in the file reader class.
This is the main class that is supposed to call the fileReader.
public class window {
public static void main(String[] args){
String[] people = readFromText.read("people.txt");
}
}
File Reader Class
public class readFromText{
public static String[] read(String textFile) throws IOException {
BufferedReader inputFile = new BufferedReader(new
FileReader(textFile));
String[] array = new String[10];
String line = inputFile.readLine().toString();
int cnt = 0;
while (line!=null){
array[cnt] = line;
line = inputFile.readLine().toString();
cnt++;
}
inputFile.close();
return array;
}
}
Is it possible to do this, this way?
Firstly your code is not correct. You can not return the String[] array for the function need String[][].
Secondly for problem about exception you just need to catch it in your main class.
try {
String[] people = readFromText.read("people.txt");
} catch (IOException e) {
e.printStackTrace();
}

Reading object from a file and saving it into ArrayList

I have a problem with reading specific object from a file and saving it into ArrayList.
First I write a single customer using writeCustomer(). Then I write all records from List customerList and save them to the file. This works great.
Then I want to read the saved file so I read one line using readCustomer(). This method returns one Customer and then I want to return a list with all Clients using readData() and read it, I have nullPointerException in line list.add(readCustomer(bufferedReader));
My Class Customer has one constructor and is has an override method toString().
public class SaveCustomers {
public static void main(String[] args) throws IOException {
List<Customers> customersList = new ArrayList<>();
customersList.add(new Customers("ABC", 10));
customersList.add(new Customers("SGS", 20));
customersList.add(new Customers("FSD", 30));
try (PrintWriter out = new PrintWriter("customer.txt", "UTF-8"))
{ writeData(customersList, out); }
BufferedReader bufferedReader = new BufferedReader(new FileReader("customer.txt"));
List<Customers> newList = readData(bufferedReader);
for(Customers c: newList){
System.out.println(c);
}
}
private static void writeCustomer(PrintWriter out, Customers customers){
out.println(customers.getName()+"|"+customers.getTarrif());
}
private static void writeData(List<Customers> customersList, PrintWriter out){
for(Customers c:customersList){
writeCustomer(out, c);
}
}
public static Customers readCustomer(BufferedReader bufferedReader) throws IOException {
String line = bufferedReader.readLine();
String [] tokens = line.split("\\|");
String name = tokens[0];
int time = Integer.valueOf(tokens[1]);
return new Customers(name, time);
}
public static List<Customers> readData(BufferedReader bufferedReader) throws IOException {
List<Customers> list = new ArrayList<>();
while (bufferedReader.readLine() != null) {
list.add(readCustomer(bufferedReader));
}
return list;
}}
You are close to the solution ;)
In method :
readData(BufferedReader bufferedReader)
Just change this line
for(Customers l : list) {
to this one :
while (bufferedReader.ready()) {

How to use ArrayList while adding something to another Class's constructor ?

I'm try to create one simple reservation system, we'll read a file, then we'll add Train, Bus, etc., then we'll writer everything to output.
import java.io.*;
import java.util.*;
public class Company
{
private static ArrayList<Bus> bus = new ArrayList<Bus>();
static int buscount = 0, traincount = 0;
public static void main (String[] args) throws IOException
{
FileParser();
}
public Company()
{
}
public static void FileParser()
{
try {
File file = new File(); //i fill this later
File file2 = new File(); // i fill this later
FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(file2);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String line;
while ((line = br.readLine()) != null)
{
String[] splitted = line.split(",");
if(splitted[0].equals("ADDBUS"))
{
bus.add(buscount) = Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]);
}
}
}
catch (FileNotFoundException fnfe) {
}
catch (IOException ioe) {
}
}
}
I try to read the file line by line. For example one of the line is "ADDBUS,78KL311,10,140,54" I split the line for "," then i try to add every pieces of array to Bus' class' constructor but i couldn't figured it out.
My Bus Class is like `
public class Bus extends Vehicle{
private String command;
private String busName;
private String busPlate;
private String busAge;
private String busSpeed;
private String busSeat;
public Bus(String command, String busname, String busplate, String busage, String busspeed, String busseat)
{
this.command = command;
this.busName = busname;
this.busPlate = busplate;
this.busAge = busage;
this.busSpeed = busspeed;
this.busSeat = busseat;
}
public String getBusName() {
return busName;
}
public void setBusName(String busName) {
this.busName = busName;
}
public String getBusPlate() {
return busPlate;
}
public void setBusPlate(String busPlate) {
this.busPlate = busPlate;
}
public String getBusAge() {
return busAge;
}
public void setBusAge(String busAge) {
this.busAge = busAge;
}
public String getBusSpeed() {
return busSpeed;
}
public void setBusSpeed(String busSpeed) {
this.busSpeed = busSpeed;
}
public String getBusSeat() {
return busSeat;
}
public void setBusSeat(String busSeat) {
this.busSeat = busSeat;
}
public String getCommand() {
return command;
}
public void setCommand(String command) {
this.command = command;
}
}
can someone show me a way to solve this problem?
Thank you,
You are missing the keyword new to create a new instance of the class:
bus.add(new Bus(...));
You can add items to ArrayList like this
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
you were missing new keyword before Bus constructor call. Then you can increment the counter (or do whatever)
bus.add( new Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
buscount++;
try to add new Bus(...)
bus.add( new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));
As I understand if you want to call constructor you need to call new Bus(parms).
when you say new it will call constructor of your class
when you say this() again it going to call enclosing class' constructor
if you say super() it will call super class' constructor.
if you want it into a map order by counter you can use this:
Map(Integer, Bus) busPosition = new HashMap<>();
busPosition.put(buscount, new
Bus(splitted[0],splitted[1],splitted[2],splitted[3],splitted[4],splitted[5]));

ArrayList saved to textfile

I want to save the contents of my arraylist to a textfile. What I have so far is shown below, however instead of adding x.format("%s%s", "100", "control1"); to the textfile, I want to add objects from an arraylist, how do I go about this?
import java.util.*;
public class createfile
{
ArrayList<String> control = new ArrayList<String>();
private Formatter x;
public void openFile()
{
try {
x = new Formatter("ControlLog.txt");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error: Your file has not been created");
}
}
public void addRecords()
{
x.format("%s%s", "100", "control1");
}
public void closeFile()
{
x.close();
}
}
public class complete
{
public static void main(String[] args)
{
createfile g = new createfile();
g.openFile();
g.addRecords();
g.closeFile();
}
}
Both ArrayList and String implement Serializable. Since you have an ArrayList of string you can write it to the file like this:
FileOutputStream fos = new FileOutputStream("path/to/file");
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(myArrayList); //Where my array list is the one you created
out.close();
Here is a really good tutorial that shows you how to write java objects to a file.
The written objects can be read back from the file in a similar way.
FileInputStream in = new FileInputStream("path/to/file");
ObjectInputStream is = new ObjectInputStream(in);
myArrayList = (ArrayList<String>) is.readObject(); //Note that you will get an unchecked warning here
is.close()
Here is a tutorial on how to read objects back from a file.

Categories

Resources