Null pointer when reading a Properties file from another folder [duplicate] - java

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
My application will check if a Properties file exists and create one if not.
try{
// create new file
String path="c:\\temp\\LaserController.properties";
File file = new File(path);
String comport = "Comport=COM1";
String Parity = "parity=none";
String baud = "baud=9600";
String Stopbits = "StopBits=0";
String databits = "DataBits=8";
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
// write in file
bw.write(comport);
bw.newLine();
bw.write(Parity);
bw.newLine();
bw.write(baud);
bw.newLine();
bw.write(Stopbits);
bw.newLine();
bw.write(databits);
// close connection
bw.close();
}
But when i try to read the properties file like this i get a Null pointer.
else {
Properties prop = new Properties();
InputStream input = LaserControllerUI.class.getResourceAsStream("c:\\temp\\LaserController.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty(Comport+"comport"));
System.out.println(prop.getProperty("Parity"));
System.out.println(prop.getProperty("Baud"));
input.close();
}
}catch(Exception e){
System.out.println(e);
}
}
It fails on the InputStream input line but i dont know why. the file exists and my application can access it because it put it there in the first place. What am i doing wrong?
The file has to be in a location that is accessible to users to change parameters.

getResourceAsStream method needs a "class-path relative" name. You are providing an absolute path. Try to use FileInputStream instead.
E.g:
InputStream input = new FileInputStream("c:\\temp\\LaserController.properties");

I suggest using Properties.save() to ensure it is written in a format when can be read.
I suggest you look at the text file to see what was written.
BTW The properties are case sensitive. you write
Comport
parity
baud
but you read
Comport+"comport"
Parity
Baud
so they will all be null.

Move that file to resource folder or add that folder as resource folder
getClass().getClassLoader().getResourceAsStream("LaserController.properties")

Related

Java how to add new line to file [duplicate]

This question already has answers here:
How to append text to an existing file in Java?
(31 answers)
Closed 2 years ago.
Im trying to add multiple strings to a file.
FileWriter myWriter = new FileWriter("cache.txt");
BufferedWriter bw=new BufferedWriter(myWriter);
bw.write(marker);
bw.newLine();
bw.close();
But whenever I write a new String it keeps overriding.
So I only have one string in my file.
How would I make it add a new line to the file.
Here is an example
What should happen.
file(cache.txt):
fd174d5b4bbc85295a649f9d70a4adf4
9b854017b04d62732ac00f2ee8007968
...
What happens for me
file(cache.txt):
9b854017b04d62732ac00f2ee8007968(last entry)
Because that's what BufferedWriter's .write is supposed to do.
If the file doesn't exists, create and write to it.
If the file exists, truncate (remove all content) and write to it
To append, use this:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("myfile.txt", true)));
out.println("text");
out.close();
} catch (IOException e) {
//exception handling
}
Use the "append" flag to the FileWriter constructor:
FileWriter myWriter = new FileWriter("cache.txt", true);
Otherwise the file will be reset to the beginning each time it is opened.

How can I modify a text file inside a Jar file while runtime? [duplicate]

This question already has answers here:
Modifying a file inside a jar
(14 answers)
Closed 7 years ago.
Well as the question says, How is that possible?
This file is my proyect structure (I'm using eclipse).
When exported as Jar, I can access and print the "root.ini" content through console with the code below but, How can I write to that file while runtime?
This method is called from 'Main.java'
private void readRoot(){
InputStream is = getClass().getResourceAsStream("/img/root.ini");
BufferedReader br = null;
br = new BufferedReader(new InputStreamReader(is));
String path = "";
try {
path = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(path);
}
What I'm actually trying to do is get some text from a JTextField, and save it to "root.ini" file.
So when I try to write to that file like this
private void writeRoot() {
URL u = getClass().getResource("/img/root.ini");
File f = null;
try {
f = new File(u.toURI());
FileWriter fw = new FileWriter(f.getAbsolutePath());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Sample text"); //This String is obtained from a TextField.getText();
bw.close();
fw.close();
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
And throws me this error
C:\Users\Francisco\Desktop\tds>java -jar TDS.jar
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: URI is not hierarchical
at java.io.File.(Unknown Source)
at main.Configuracion.writeRoot(Configuracion.java:99)
at main.Configuracion.access$1(Configuracion.java:95)
You can't change any content of a jar which is currently used by a jvm. This file is considered locked by the operating system and therefore can't be changed.
I suggest to write this file outside your jar file. e.g. in a /conf directory relative to the current working dir.

Java - How to Clear a text file without deleting it?

I am wondering what the best way to clear a file is. I know that java automatically creates a file with
f = new Formatter("jibberish.txt");
s = new Scanner("jibberish.txt");
if none already exists. But what if one exists and I want to clear it every time I run the program? That is what I am wondering: to say it again how do I clear a file that already exists to just be blank?
Here is what I was thinking:
public void clearFile(){
//go through and do this every time in order to delete previous crap
while(s.hasNext()){
f.format(" ");
}
}
Best I could think of is :
Files.newBufferedWriter(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
and
Files.newInputStream(pathObject , StandardOpenOption.TRUNCATE_EXISTING);
In both the cases if the file specified in pathObject is writable, then that file will be truncated. No need to call write() function. Above code is sufficient to empty/truncate a file.This is new in java 8.
Hope it Helps
You could delete the file and create it again instead of doing a lot of io.
if(file.delete()){
file.createNewFile();
}else{
//throw an exception indicating that the file could not be cleared
}
Alternately, you could just overwrite the contents of the file in one go as explained in the other answers :
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
Also, you are using the constructor from Scanner that takes a String argument. This constructor will not read from a file but use the String argument as the text to be scanned. You should first created a file handle and then pass it to the Scanner constructor :
File file = new File("jibberish.txt");
Scanner scanner = new Scanner(file);
If you want to clear the file without deleting may be you can workaround this
public static void clearTheFile() {
FileWriter fwOb = new FileWriter("FileName", false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}
Edit: It throws exception so need to catch the exceptions
You can just print an empty string into the file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();
type
new PrintWriter(PATH_FILE).close();
Better to use this:
public static void clear(String filename) throws IOException {
FileWriter fwOb = new FileWriter(filename, false);
PrintWriter pwOb = new PrintWriter(fwOb, false);
pwOb.flush();
pwOb.close();
fwOb.close();
}

Reading a text file in a .jar-application [duplicate]

This question already has answers here:
getResourceAsStream returns null
(26 answers)
Closed 8 years ago.
With this code I want a .jar-file to read the text-file "file.txt" which is located in the jar in folder data. This is a application is programmed with Processing, so all files I want to read are in the data folder. Can anybody explain why I get a NullPointerException? The file exists and contains text.
import java.io.*;
void setup() {
size(500, 500);
try {
// HERE I TRY TO READ THE FILE WHICH IS LOCATED IN THE JAR FILE IN THE FOLDER "DATA"
InputStream is = getClass().getResourceAsStream("/data/file.txt");
// HERE I GET A NULL-POINTER-EXCEPTION BECAUSE THE FILE CANNOT BE READ (IS = NULL, WHY IS THE INPUT STREAM NULL?)
BufferedReader br = new BufferedReader(new InputStreamReader(is));
// THE FIRST LINE OF THE DOCUMENT IS READ AND PRINTED IN THE CONSOLE
String read = br.readLine();
br.close();
println(read);
}
catch (IOException e) {
// IF THE FILE DOESN'T EXIST AN IO-EXCEPTION WILL BE CAUGHT
println("Error reading file");
}
}
getClass().getResourceAsStream("/data/file.txt"); returns null, because it uses that class' system loader which can't see your jar. Use instead
YourClassName.class.getResourceAsStream("/data/file.txt");

How do you get the text in system.output.println? [duplicate]

This question already has answers here:
How do I create a file and write to it?
(35 answers)
Closed 8 years ago.
On the output part of my IDE (where all the system.out.println textx appear), I have several lines of text. I want to get them and save them to a text file. What would be the possible code for this?
use System#setOut() to redirect output to FileOutputStream to redirect System output to file
// for restore purpose
PrintStream oldOutStream = System.out;
PrintStream outFile = new PrintStream(
new FileOutputStream("/path/to/file.txt", true));
System.setOut(outFile);
System.out.println("this will goto file");
I assume you know about logging framework and you are not trying to use this for logging something
Yo can replce all sop with fileoutput strem and write everything in file
if you want to write log then you can use log4j
String content = "This is the content to write into file";
File file = new File("filename.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(content);
bw.close();

Categories

Resources