Java file Formatting proper order - java

I am writing a program which requires the opening of a file, adding to it, and then closing it. For some reason when I try to do so, I get a nullPointerException.
Here is what I have in the main class:
public static filer f = new filer();
and then:
f.addStuff("hi");
f.closeFile();
now here is what I have in the file class, which is where I think the problem is right now:
public class filer {
private static Formatter f;//to add to file
private static Scanner s; //to read file
public static File file;
private static boolean ftf = false;
public static void openFile() {
try{ //exception handling
file = new File("jibberish.txt");
//shows if file created
System.out.println("File created: "+ ftf);
// deletes file from the system
file.delete();
// delete() is invoked
System.out.println("delete() method is invoked");
// tries to create new file in the system
ftf = file.createNewFile();
// print
System.out.println("File created: "+ ftf);
Formatter f = new Formatter(file);
Scanner s = new Scanner(file);
FileReader r = new FileReader(file);
/*
f = new Formatter("jibberish.txt"); //will automatically create jibberish.txt if no exist
s = new Scanner("jibberish.txt");
*/ //don't us these because scanner will take type string, easier to clear all other way
}
catch(IOException ioe){
System.out.println("Trouble reading from the file: " + ioe.getMessage());
}
}
public static void addStuff(String toAdd){
f.format("%s ", toAdd);
System.out.printf("%s added", toAdd);
}
public static void closeFile(){ //need to do this to avoid errors
f.close();
s.close();
}
the rest of the class works, i have all the proper imports and stuff
oh and of course here is what comes out of the console:
File created: false
delete() method is invoked
File created: true
Exception in thread "main" java.lang.NullPointerException
at filer.addStuff(filer.java:48)
at transMain.main(transMain.java:40)

You get a NullPointerException because when you call the addStuff method, f has not been initialized and is therefore null. Calling a method on a reference to a null object will result in a NullPointerException.
The problem is with the following line in openFile. You are creating a new local variable called f which hides the field named f declared at class level :
Formatter f = new Formatter(file);
Change the above line as follows so that the class level field f is the one that is initialized in openFile:
f = new Formatter(file);

Related

NullPointerException in Scanner when reading a Serializable Object from File

I am trying to edit an array of objects after reading them by using Serializable.
The code works fine for new instance of my object but gives a NullPointer exception when I try to edit the object read from file.
public class ShoppingCenter implements Serializable{
// I cant write to file without transient
transient Scanner scan=new Scanner (System.in);
private static final long serialVersionUID = 6529685098267757692L;
//This is the edit details method which will be used to modify the details
public void editDetails()
{
System.out.println("The details are as follows:");
System.out.println("*Name is "+ name);
System.out.println("\t(1-Edit 2-Continue)");
// *******This is where it gives the exception********
if (scan.nextInt()==1)
{System.out.println("\t Write the new value..");
name=scan.next();
System.out.println("Done..");}
System.out.println("*Location is "+ location);
System.out.println("\t(1-Edit 2-Continue)");
if (scan.nextInt()==1)
{System.out.println("\t Write the new value..");
location=scan.next();
System.out.println("Done..");}
}
This is the stack Trace.
java.lang.NullPointerException
at ShoppingCenter.editDetails(ShoppingCenter.java:40)
at Part3Main.searchObject(Part3Main.java:99)
at Part3Main.init(Part3Main.java:130)
at Part3Main.main(Part3Main.java:189)
Here is my driver.
public void init(){
readFile("shoppingCenter");
}
public void readFile(String name){
try{
FileInputStream fis = new FileInputStream(name);
ObjectInputStream ois = new ObjectInputStream(fis);
sc = (ShoppingCenter[]) ois.readObject();
ois.close();
System.out.println("The Object was succesfully read from the file");
//System.out.println(sc[1].toString());
//System.out.println(sc.toString());
}
catch (Exception ex){
ex.printStackTrace();
}
}
A little help would be really appreciated.. Thanks ..

How to use a Path object as a String

I'm looking to try and create a Java trivia application that reads the trivia from separate question files in a given folder. My idea was to use the run() method in the FileHandler class to set every text file in the folder into a dictionary and give them integer keys so that I could easily randomize the order at which they appear in the game. I found a simple chunk of code that is able to step through the folder and get the paths of every single file, but in the form a Path class. I need the paths (or just the names) in the form a String class. Because I need to later turn them into a file class (which excepts a String Constructor, not a Path). Here is the chunk of code that walks through the folder:
public class FileHandler implements Runnable{
static Map<Integer, Path> TriviaFiles; //idealy Map<Integer, String>
private int keyChoices = 0;
public FileHandler(){
TriviaFiles = new HashMap<Integer, Path>();
}
public void run(){
try {
Files.walk(Paths.get("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
TriviaFiles.put(keyChoices, filePath);
keyChoices++;
System.out.println(filePath);
}
});
} catch (FileNotFoundException e) {
System.out.println("File not found for FileHandler");
} catch (IOException e ){
e.printStackTrace();
}
}
public static synchronized Path getNextValue(){
return TriviaFiles.get(2);
}
}
There is another class named TextHandler() which reads the individual txt files and turns them into questions. Here it is:
public class TextHandler {
private String A1, A2, A3, A4, question, answer;
//line = null;
public void determineQuestion(){
readFile("Question2.txt" /* in file que*/);
WindowComp.setQuestion(question);
WindowComp.setAnswers(A1,A2,A3,A4);
}
public void readFile(String toRead){
try{
File file = new File("/home/chris/JavaWorkspace/GameSpace/bin/TriviaQuestions",toRead);
System.out.println(file.getCanonicalPath());
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
question = br.readLine();
A1 = br.readLine();
A2 = br.readLine();
A3 = br.readLine();
A4 = br.readLine();
answer = br.readLine();
br.close();
}
catch(FileNotFoundException e){
System.out.println("file not found");
}
catch(IOException e){
System.out.println("error reading file");
}
}
}
There is stuff I didn't include in this TextHandler sample which is unimportant.
My idea was to use the determineQuestion() method to readFile(FileHandler.getNextQuestion).
I am just having trouble working around the Path to String discrepancy
Thanks a bunch.
You can simply use Path.toString() which returns full path as a String. But kindly note that if path is null this method can cause NullPointerException. To avoid this exception you can use String#valueOf instead.
public class Test {
public static void main(String[] args) throws NoSuchFieldException, SecurityException {
Path path = Paths.get("/my/test/folder/", "text.txt");
String str = path.toString();
// String str = String.valueOf(path); //This is Null Safe
System.out.println(str);
}
}
Output
\my\test\folder\text.txt

use constructors to create a text file and take user input for filename

main Class Which is accepting user input as a file name.
public class Main {
public static void main(String args[]) throws Exception{
FileOperator fileObject = new FileOperator();
System.out.println(Strings.userMenu);
#SuppressWarnings("resource")
Scanner scan= new Scanner(System.in);
String userInput = scan.next();
if(userInput.isEmpty()){
System.out.println(Strings.inputExpected);
}
else{
fileObject.fileOperator(userInput);
}
}
}
/* It is a generic file which takes user input as a file name and saves the file with that name.*/
public class FileOperator {
/*
* The Below Method fileOperator will access filename as a input from user.
* Checks if the file is available in given path.
* If File is available then file exist message will be printed.
* Else new file with that name will b created.
* If user enters nothing then error message will be popped up.
*/
public void fileOperator(String userInputFileName) throws Exception {
File newFileName = new File(userInputFileName);
if(newFileName.exists() && !newFileName.isDirectory()) {
System.out.println(Strings.fileExists);
}
else if (newFileName.createNewFile()){
System.out.println(Strings.fileCreated);
}
else if(newFileName.equals("")){
System.out.println("");
}
else{
System.out.println(Strings.errorForFileNotCreated);
}
}
}
But the problem is I want to create a file object using a constructor. I am very new to java so kindly help with this.
Create constructor in FileOperator class:
public class FileOperator{
public FileOperator(String filename){
// here write fileOperator method code and delete that method
}
}
in main delete FileOperator fileObject = new FileOperator(); // and write in else part
{
FileOperator fileObject = new FileOperator(userInput)
}

fill a file inside a inner class

I'm quiet new to java and I'm not even sure if the title makes any sense.
Anyway how do I gain access to a file inside of onStatus?
I'm just trying to write into a file in that function so in the code below "T_file.length()" the "T_file" cannot be resolved.
public static void main (){
foo("file_name");
}
foo(String fileName)
{
try{
final File T_file = new File (fileName);
final FileWriter fw = new FileWriter(fileName);
final BufferedWriter bw = new BufferedWriter (fw);
}catch (IOException e){}
StatusListener listener = new StatusListener(){
public void onStatus(Status status){
if (T_file.length() > 100){
System.out.println ("I have access here");
}
}
}
}
"T_file.length()" the "T_file" cannot be resolved
This is because T_file is not in the scope of onStatus. You declare T_file in the foo method, but then create a new StatusListener in which you redefine the onStatus, but the compiler still see StatusListener as an other class.
A workaround would be to declare the variable globally in your class, then access it specifying the name of your Class.this.T_file. Here an example :
public class Foo {
File T_file;
public static void main (){
new Foo("file_name");
}
Foo(String fileName)
{
T_file = new File (fileName);
StatusListener listener = new StatusListener(){
public void onStatus(Status status){
if (Foo.this.T_file.length() > 100){
System.out.println ("I have access here");
}
}
};
}
}
This example would compile.
Notice that I added a ; at the end of the StatusListener, else it would not compile.

How to call instance method in static method

So what am I trying to do is to read a .txt file and add some record on it using eclipse. I set my resource which I named it as "fileName" as private and when I try to call it in main method, there is some error. Here is my code:
public class FileController {
private String fileName;
public FileController() {
}
public FileController(String fileName) {
fileName = "student.txt";
}
public void readLine() {
try {
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
// read in the file line by line
while (sc.hasNextLine()) {
System.out.println(sc.nextLine());
}
fr.close();
} catch (FileNotFoundException exception) {
System.out.println("The file " + fileName + " was not found.");
} catch (IOException exception) {
System.out.println(exception);
}
}
public void writeLine() {
try {
// create the PrintWriter
FileWriter fw = new FileWriter(fileName, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
// write value out to the file
outFile.println("Coke is nice");
outFile.println("Diet Coke is even better cos won't put on weight =)");
// close the file
outFile.close();
System.out.println("File created: " + fileName);
} catch (IOException exception) {
System.out.println(exception);
}
}
public static void main(String[] args) {
FileController fs = new FileController();
fs.readLine();
fs.writeLine();
}
}
Anybody can give me some clues? These codes keep giving me NullPointerException error. I know it's from the FileController fs = new FileController() that line, but I do not know how to call instance method in static method.
Try:
public FileController() {
fileName = "student.txt";
}
public FileController(String fileName) {
this.fileName = filename;
}
I think your constructor should look like this:
public FileController(String fileName) {
this.fileName = fileName;
}
And the no-arg constructor like this:
public FileController() {
this("student.txt");
}
FileController fs = new FileController();
should be
FileController fs = new FileController("fileName");
You should also edit you constructor like this.Since class variable fileName and parameter name in constructor has same name you must have to use "this" keyword for assignment .
public FileController(String fileName) {
this.fileName = fileName;
}
If the parameter name and the class variable name is different you can do this.
public FileController(String name) {
fileName = name;
}
You are not passing the name of the file in the constructor. You should pass a valid file name in there for your logic to work properly
You need to call your constructor with an argument, or your default constructor should provide a default filename, for instance, in your main:
FileController fs = new FileController("somefile.txt")
And your constructor needs to be changed to:
public FileController(String filename) {
this.fileName = filename;
}
And you could change your default constructor:
public FileController() {
this("someDefaultFile.txt");
}
Keep in mind that the later option only makes sense if there is a default file to look for, otherwise you should explicitly pass the name of the file.
Instance methods can be accessed in static methods using the object reference of the class whose method you are trying to invoke.
Hence using new keyword as you have rightly pointed out will resolve your issue.
Problem is by calling new FileController(); you didn't initialized fileName field.
You probably wanted your constructors look like this:
public FileController() {
this.fileName = "student.txt";
}
public FileController(String fileName) {
this.fileName = fileName;
}
Then will be calling new FileController(); legit.

Categories