FileInputStream fails on properties file - java

This properties file in PROJECT/resources/properties.properties can be read and show its content with:
public void showFileContent(String fileName){
File file = new File (fileName);
FileInputStream input = null;
if(file.exists()){
int content;
try {
input = new FileInputStream(fileName);
while ((content = input.read()) != -1) {
System.out.print((char) content);
}
} catch (IOException e) {
e.printStackTrace();
}finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
}
But it fails with a null pointer exception at properties.load with that code
public Properties getProperties(String fileName, Properties properties){
File file = new File (fileName);
InputStream input = null;
if(file.exists()){
try {
input = new FileInputStream(fileName);
properties.load(input);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}else{
System.out.println("Error : properties File " + fileName + " not found");
}
return properties;
}
even when input is set to
input = this.getClass().getClassLoader().getResourceAsStream(fileName)
anyone knows why that can be for a properties text file at the same path for both methods ?

Since the first code snippet works, it seems properties is passed as null to the getProperties() method, resulting in NullPointerException.
Ideally, we shouldn't be passing the properties at all. We just need to create a new object and return it.

Related

How to get file jpg properties in Android Studio

Firstly I get an ArrayList using the method getFilePaths.
method { List out all images from SD card.}
How to continue?
At phone, when you see details over image, you can see:
tittle, hour, width, height, orientation, fileSize, path...
I want get all attributes/details/properties of a file jpg and save them in variables.
I tried do this: Properties Class Java but I think that's not the right way
You can retrieve Properties from File like below code add your file into below code and get Properties object
Properties prop = new Properties();
// load a properties file
prop.load(input);
private void retrievePropertiesFromFile(){
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/CHETAN");
String fname = "mytext.txt";
File myFile = new File (myDir, fname);
InputStream input = null;
try {
input = new FileInputStream(myFile);
Properties prop = new Properties();
// load a properties file
prop.load(input);
// get the property value and print it out
Log.i(getClass().getSimpleName(),prop.getProperty("text"));
Log.i(getClass().getSimpleName(),prop.getProperty("textstyle"));
Log.i(getClass().getSimpleName(),prop.getProperty("typeface"));
Log.i(getClass().getSimpleName(),prop.getProperty("typeface"));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Ok, I using this simple code and it show null in property text:
File imageJPG = new File("/storage/emulated/0/WhatsApp/Media/WhatsApp Images","6gMRtQyY.jpg");
if(imageJPG.isFile()){
System.out.println("its file");
System.out.println("image: "+imageJPG);
}else{
System.out.println("no");
}
InputStream input = null;
try {
input = new FileInputStream(imageJPG);
Properties prop = new Properties();
prop.load(input);
// get the property value and print it out
System.out.println("property text: "+prop.getProperty("text"));
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Console:
I/System.out: its file
I/System.out: image: /storage/emulated/0/WhatsApp/Media/WhatsApp Images/6gMRtQyY.jpg
I/System.out: property text: null

How create multiple serialization?

How create multiple serialization ? Now the system write just last record to txt. I want create simple DB that will contain customers info. And what you think, about this method of storing data in txt. ?
private static void WriteCustomers(){
System.out.println("|______Registration module______|");
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
CustomerManagement obj = new CustomerManagement();
CustomerManagementD customerManagementD = new CustomerManagementD();
customerManagementD.setFirstName(firstName);
customerManagementD.setLastName(lastName);
.....
obj.serializeCustomers(customerManagementD);
}catch (IOException e){
e.getMessage();
}
}
public void serializeCustomers(CustomerManagementD customerManagementD) {
FileOutputStream fout = null;
ObjectOutputStream oos = null;
try {
fout = new FileOutputStream("CustomerManagement.txt");
oos = new ObjectOutputStream(fout);
oos.writeObject(customerManagementD);
System.out.println("Done");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (fout != null) {
try {
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (oos != null) {
try {
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Last question, If I use serialization, I will be able to Edit and Remove stored particular objects?
A txt-file is used for text-only. The ObjectOutputStream stores more than then fields: it stores the classname (and serialVersionUID if present). Try to use .dat what is a generic extension for databases or datas.
You call the method serializeCustomers where Customers is plural and let me think we can store multiple Customer, but the parameter does not allow to use multiple customers. Instead, I suggest, to store a Set (like a LinkedHashSet) to store multiple customers, and yes, you can read and write to the LinkedHashSet.
SOLUTION
private static void WriteCustomers(List<CustomerManagementD> list){
try {
System.out.println("First name: ");
String firstName = reader.readLine();
System.out.println("Last name: ");
String lastName = reader.readLine();
.....
// serialize collection of customers
customerManagementDArraysList.add(new CustomerManagementD(
customerID,firstName,lastName,email,contactNo));
ObjectOutputStream outStream = null;
try {
outStream = new ObjectOutputStream(new FileOutputStream(file));
for (CustomerManagementD p : list) {
outStream.writeObject(p);
}
} catch (IOException ioException) {
System.err.println("Error opening file.");
} finally {
try {
if (outStream != null)
outStream.close();
} catch (IOException ioException) {
System.err.println("Error closing file.");
}
}
}else if (finalcheck.equals("2")){
Adminswitch();
}
System.out.println("|______Customer was successfully saved______|\n Press 'Enter' to continue...");
String absentinput = reader.readLine();
Adminswitch();
}catch (IOException e){
e.printStackTrace();
}
}
private static ArrayList ViewCustomer(){
try{
FileInputStream fis = new FileInputStream(file);
ObjectInputStream oos =new ObjectInputStream(fis);
ArrayList<CustomerManagementD> customerManagementDArraysList = new ArrayList<>();
try {
while (true) {
CustomerManagementD cmd = (CustomerManagementD) oos.readObject();
customerManagementDArraysList.add(cmd);
}
}catch (EOFException e){
e.getMessage();
}
{
while (file.canRead()){
for (CustomerManagementD cmd : customerManagementDArraysList) {
System.out.println("Customer ID: " + cmd.getCustomerID() +
" First Name: " + cmd.getFirstName() +
" Last Name: " + cmd.getLastName()+....);
}
break;
}
}
}catch (IOException e){
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();}
return null;
}

Don't find my file.properties

I try a lot of thinks to find the fail but i don't know how I can do it. my code is:
//DominioLlamadaRedSys.java
Properties d = new Properties();
InputStream entrada = null;
try {
entrada = new FileInputStream("prop/datosApp.properties");
d.load(entrada);
System.out.println(d.getProperty("TXD.endPointUrl"));
} catch (IOException ex) {
System.out.println("ERROR: "+ ex.getMessage());
} finally {
if (entrada != null) {
try {
entrada.close();
} catch (IOException e) {
}
}
}
I call the file inside a class in "com.rsi.secpay.dominio" and this always catch the same exception (don't find the file), I had try to quit "prop/" (just "datosApp.properties" ) with properties files like this:
If your prop package is in your classpath, you can get the stream using the classloader:
InputStream is = DominioLlamadaRedSys.class.getResourceAsStream("/prop/datosApp.properties");

How to overwrite a file if it already exists in dropbox?

I am uploading a file in dropbox by this method:
public void upload() {
FileInputStream inputStream = null;
try {
File file = new File(Environment.getExternalStorageDirectory()
.toString() + "/write.txt");
inputStream = new FileInputStream(file);
Entry newEntry = mDBApi.putFile("/write.txt", inputStream,
file.length(), null, null);
Log.i("DbExampleLog", "The uploaded file's rev is: " + newEntry.rev);
} catch (DropboxUnlinkedException e) {
// User has unlinked, ask them to link again here.
Log.e("DbExampleLog", "User has unlinked.");
} catch (DropboxException e) {
Log.e("DbExampleLog", "Something went wrong while uploading.");
} catch (FileNotFoundException e) {
Log.e("DbExampleLog", "File not found.");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}
}
}
but when already this file exists in the folder then the file get renamed to write(1).txt
but I want that if the file already exists in the dropbox share folder then it will be replaced. What should I do now?
You can use mDBApi.putFileOverwrite instead of mDBApi.putFile

How to delete only the content of a file in Java?

How can I delete the content of a file in Java?
How about this:
new RandomAccessFile(fileName).setLength(0);
new FileOutputStream(file, false).close();
You could do this by opening the file for writing and then truncating its content, the following example uses NIO:
import static java.nio.file.StandardOpenOption.*;
Path file = ...;
OutputStream out = null;
try {
out = new BufferedOutputStream(file.newOutputStream(TRUNCATE_EXISTING));
} catch (IOException x) {
System.err.println(x);
} finally {
if (out != null) {
out.flush();
out.close();
}
}
Another way: truncate just the last 20 bytes of the file:
import java.io.RandomAccessFile;
RandomAccessFile file = null;
try {
file = new RandomAccessFile ("filename.ext","rw");
// truncate 20 last bytes of filename.ext
file.setLength(file.length()-20);
} catch (IOException x) {
System.err.println(x);
} finally {
if (file != null) file.close();
}
May problem is this leaves only the head I think and not the tail?
public static void truncateLogFile(String logFile) {
FileChannel outChan = null;
try {
outChan = new FileOutputStream(logFile, true).getChannel();
}
catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("Warning Logfile Not Found: " + logFile);
}
try {
outChan.truncate(50);
outChan.close();
}
catch (IOException e) {
e.printStackTrace();
System.out.println("Warning Logfile IO Exception: " + logFile);
}
}
Open the file for writing, and save it. It delete the content of the file.
try {
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.flush();
writer.close();
}catch (Exception e)
{
}
This code will remove the current contents of 'file' and set the length of file to 0.

Categories

Resources