Read a file using location from properties file - java

I have one file that is stored in C:/file.txt. The properties file location.properties contains only the path i.e C:/file.txt. I want to read the properties file, get the location , read the file and display everything.
But I am getting fileNotFound exception. Can anybody help me? This is my code:
package com.tcs.fileRead;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadFile {
/**
* #param args
*/
public static void main(String[] args) {
Properties prop = new Properties();
try {
prop.load(new FileInputStream("location.properties"));
//prop.load(fileIn);
String loc = prop.getProperty("fileLoc");
System.out.println(loc);
BufferedReader buffer;
buffer = new BufferedReader(new FileReader(loc));
String line;
while((line =buffer.readLine())!= null)
{
System.out.println(line);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
This is the output:
"C:\file.txt"
java.io.FileNotFoundException: "C:\file.txt" (The filename, directory name, or volume label syntax is incorrect.)
at java.io.FileInputStream.<init>(FileInputStream.java:156)
at java.io.FileInputStream.<init>(FileInputStream.java:111)
at java.io.FileReader.<init>(FileReader.java:69)
at com.tcs.fileRead.ReadFile.main(ReadFile.java:29)

You have the path surrounded with quotes in your properties file, so you are trying to open "C:\file.txt" (which is not a valid path) instead of C:\file.txt.

Related

java update txt file content line by line

I am trying to update a txt file in place, namely without creating a temp file or writing a file in a new file destination but I've tried all the solutions on stack overflow and none of these have worked so far.
It always give me an empty file as result. it simply delete all the content of the source file.
So I am trying to modify the following code, which takes two files as input, in order to take only one input (the file source) but without success.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter;
public class CopyFiles {
private static void copyFile(String sourceFileName, String destinationFileName) {
try (BufferedReader br = new BufferedReader(new FileReader(sourceFileName));
PrintWriter pw = new PrintWriter(new FileWriter(destinationFileName))) {
String line;
while ((line = br.readLine()) != null) {
line += " ENDING ";
pw.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
String destinationFileName = "destination.csv";
String sourceFileName = "source.csv";
copyFile(sourceFileName, destinationFileName);
}
}

Print all content from multiple files in directory

I have the following code seen below, this code looks through a directory and then prints all of the different file names. Now my question is, how would I go about changing my code, so that it would also print out all of the content within the files which it finds/prints? As an example, lets say the code finds 3 files in the directory, then it would print out all the content within those 3 files.
import java.io.File;
import java.io.IOException;
public class EScan {
static String usernamePc = System.getProperty("user.name");
final static File foldersPc = new File("/Users/" + usernamePc + "/Library/Mail/V2");
public static void main(String[] args) throws IOException {
listFilesForFolder(foldersPc);
}
public static void listFilesForFolder(final File foldersPc) throws IOException {
for (final File fileEntry : foldersPc.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
}
}
}
}
I tested it before posting. it is working.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* #author EdwinAdeola
*/
public class TestPrintAllFiles {
public static void main(String[] args) {
//Accessing the folder path
File myFolder = new File("C:\\Intel");
File[] listOfFiles = myFolder.listFiles();
String fileName, line = null;
BufferedReader br;
//For each loop to print the content of each file
for (File eachFile : listOfFiles) {
if (eachFile.isFile()) {
try {
//System.out.println(eachFile.getName());
fileName = eachFile.getAbsolutePath();
br = new BufferedReader(new FileReader(fileName));
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (IOException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
Logger.getLogger(TestPrintAllFiles.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
You may use Scanner to read the contents of the file
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
System.out.println(s);
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
You can try one more way if you find suitable :
package com.grs.stackOverFlow.pack10;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.Arrays;
import java.util.List;
public class EScan {
public static void main(String[] args) throws IOException {
File dir=new File("C:/your drive/");
List<File> files = Arrays.asList(dir.listFiles(f->f.isFile()));
//if you want you can filter files like f->f.getName().endsWtih(".csv")
for(File f: files){
List<String> lines = Files.readAllLines(f.toPath(),Charset.defaultCharset());
//processing line
lines.forEach(System.out::println);
}
}
}
Above code can me exploited in number of ways like processing line can be modified to add quotes around lines as below:
lines.stream().map(t-> "'" + t+"'").forEach(System.out::println);
Or print only error messages lines
lines.stream().filter(l->l.contains("error")).forEach(System.out::println);
Above codes and variations are tested.

Update/Edit property file

I am testing a library (jar) that is using property (mytest.properties). They way the library (jar) loads the property is by doing
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
So what I want to test is what happens when the property file exist and when it does not exit. In order to test this I need to edit the property file once the JVM is started. I have tried doing that and does not work. Bellow is the code I tried to edit the property file but this always returns empty string.
Content of main_mytest.properties is:
a=hello world
b=hello java
Content of mytest.properties and empty.txt is empty.
""
My Class is:
import org.apache.commons.io.IOUtils;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
public class MyPropertyFiles {
final static String resourcesPath = "./mytestproj/src/main/resources";
public static void main(String [] args) throws IOException {
Path source = Paths.get(resourcesPath + "/main_mytest.properties");
Path destination = Paths.get(resourcesPath + "/mytest.properties");
Path empty = Paths.get(resourcesPath + "/empty.txt");
try
{
Files.copy(source, destination, StandardCopyOption.REPLACE_EXISTING);
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream input = classLoader.getResourceAsStream("mytest.properties");
StringWriter writer = new StringWriter();
IOUtils.copy(input, writer, "utf-8");
String theString = writer.toString();
System.out.println("!!!!!!!!!!!!!!!! The String: \n" + theString);
}
catch (Exception e)
{
e.printStackTrace();
}
finally {
Files.copy(empty, destination, StandardCopyOption.REPLACE_EXISTING);
}
}
}
After doing some digging I don't think reloading the files in the ClassLoader after the JVM has started is allowed.

Making changes in the properties file of Java project

I need to make a change in .properties file in my Java project. This is later deployed as a jar and used by other Java project. But according to this, I see that we should not directly make the change instead create a new object. Where should we create that new object and how can we make sure that its changes are visible?
Yes that's correct if your properties files is inside a jar then you won't be able to directly change that properties file since its packaged and zipped up in an archive. Instead you can create/change the file placed on a drive and read it, I used "user.home" for an example which you can change it as your need, below is the code for the same:
package com.test.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PropertyFileReader {
private static final Logger LOGGER = LoggerFactory
.getLogger(PropertyFileReader.class);
private static Properties properties;
private static final String APPLICATION_PROPERTIES = "application.properties";
private static final String workingDir = System.getProperty("user.home");
private static File file = new File(workingDir, APPLICATION_PROPERTIES);
static {
properties = new Properties();
}
public static void main(String[] args) {
write("hello", "2");
System.out.println(read("hello"));
}
public static String read(final String propertyName) {
try (InputStream input = new FileInputStream(file)) {
properties.load(input);
} catch (IOException ex) {
LOGGER.error("Error occurred while reading property from file : ",
ex);
}
return properties.getProperty(propertyName);
}
public static void write(final String propertName,
final String propertyValue) {
try (OutputStream output = new FileOutputStream(file)) {
properties.setProperty(propertName, propertyValue);
properties.store(output, null);
} catch (IOException io) {
LOGGER.error("Error occurred while writing property to file : ", io);
}
}
}

Update only key from a key/value property file?

I am trying to tackle a program take the given input file is in.properties and I want to write it out again to a new file out.properties discarding the prefix prefix from the file contents
i.e. the contents of the input file would be
prefix.sum.code.root=/compile/pkg
the contents of the output file would be
sum.code.root=/compile/pkg
Here is my Code :
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class Dummy {
public static void main(String args[])
{
Properties prop =new Properties();
try{
//load a property file
prop.load(new FileInputStream ("C:\\Users\\user\\Desktop\\ant\\Filtering\\input.properties"));
for (String key : prop.stringPropertyNames()){
prop.remove(key);
}
prop.store(new FileOutputStream("C:\\Users\\user\\Desktop\\ant\\Filtering\\output.properties"), null);
}catch (IOException e)
{
e.printStackTrace();
}
}}
The returning null value for the 'KEY' and i am not able to update new value into this feild
You should be able to do this fairly easy using Properties.stringPropertyNames and Hashtable.remove, as Properties is a subclass of Hashtable.
final Properties properties = ...;
for (final String name : properties.stringPropertyNames()) {
if (name.startsWith("prefix.")) {
properties.setProperty(name.substring(6, name.length()), properties.remove(name));
}
}

Categories