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));
}
}
Related
I have to write a small Java class which has to check a xml file for duplicate entries.
The XML file has a key value with a German word and an English translation. It's about 20.000 lines.
Example:
<properties>
<entry key="Auto">car</entry>
<entry key="Bus">bus</entry>
<entry key="Auto">car</entry>
<entry key="Haus">House</entry>
</properties>
How can I read/ import the file and test them afterwards for multiple entries. My code finds all elements, but not in the right order.
This is my code to read the file.
package translation;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Enumeration;
import java.util.InvalidPropertiesFormatException;
import java.util.Properties;
public class doubleTest {
public static void main(String[] args)
{
try {
File file = new File("C://GER_EN.xml");
FileInputStream fileInput = new FileInputStream(file);
Properties properties = new Properties();
properties.loadFromXML(fileInput);
Enumeration enuKeys = properties.keys();
while(enuKeys.hasMoreElements()) {
String key = (String) enuKeys.nextElement();
String value = properties.getProperty(key);
System.out.println(key ); //+ ": " + value
}
fileInput.close();
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (InvalidPropertiesFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
This is my output for the above xml example.
Auto: car
Bus: bus
Haus: house
Thanks a lot in advance :)
final Set<String> keySet = new HashSet<>();
for (final Enumeration<Object> keys = properties.keys();
keys.hasMoreElements(); ) {
final String key = (String) keys.nextElement();
if (keySet.contains(key)) {
// duplicate key!
}
}
I am currently working on a machine learning project. I have a package/directory of java files and i want to read their contents. Later, i will apply other methods to achieve results.
The problem is that the given code reads the txt files, however, when i pass the directory containing java files it doesn't work properly. Following is what I did
I read the names of all files in a directory.
As every directory has different number of files and different structure of files and folders inside it. I am looking for a generic solution.
Next, I read the contents of every file and put it in a list or MAP or whatever
The given code is as follows. I have written 3 methods.
This method list all files in a directory and make a set
// it will list all files in a directory.
public Collection<File> listFileTree(File dir) {
Set<File> fileTree = new HashSet<File>();
for (File entry : dir.listFiles()) {
if (entry.isFile())
fileTree.add(entry);
else
fileTree.addAll(listFileTree(entry));
}
return fileTree;
}
Here using the above method i have tried to read the contents of each file.
File file = new File("C:\\txt_sentoken");// c\\japa..if i use it code only show directory files
Iterator<File> i = Util.listFileTree(file).iterator();
String temp = null;
while(i.hasNext()){
temp = Util.readFile(i.next().getAbsolutePath().toString());
System.out.println(temp);
}
}
This is the readFile method
// using scanner class for reading file contents
public String readFile(String pathname) throws IOException {
File file = new File(pathname);
StringBuilder fileContents = new StringBuilder((int)file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
If i pass a directory (in File file = new File("C:\\txt_sentoken");) containing txt files this code works but for java or c++ or other code directories or packages it doesn't.
Can anyone guide me in refining this code? Also if there is any API or generic solution available please share.
Use Java NIO.2 to achieve your goal.
If you need any filtering you can put checks in the FileVisitor.
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;
public class Test {
public static void main(String... args) {
try {
System.out.println(readAllFiles("")); // <----- Fill in path
} catch (IOException e) {
e.printStackTrace();
}
}
public static Map<Path, List<String>> readAllFiles(String path) throws IOException {
final Map<Path, List<String>> readFiles = new TreeMap<>();
Files.walkFileTree(Paths.get(path), new SimpleFileVisitor<Path>() {
#Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Objects.requireNonNull(file);
readFiles.put(file, Files.readAllLines(file, StandardCharsets.UTF_8));
return FileVisitResult.CONTINUE;
}
});
return readFiles;
}
}
A Java 8 - also sorted - solution would be:
public static Map<Path, List<String>> readAllFiles(String path) throws IOException {
return Files.walk(Paths.get(path)).filter(p -> !Files.isDirectory(p)).collect(Collectors.toMap(k -> k, k -> {
try {
return Files.readAllLines(k);
} catch (IOException e) {
throw new RuntimeException(e);
}
} , (u, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", u));
} , TreeMap::new));
}
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);
}
}
}
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.
I'm trying to set my database property, so in the future users could change it if they want to change the route of the database. The problem is when I try to set something with full width colon, which always add a backslash escape character .
I've tried normal and double escape, but it doesn't work.
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class SetProps {
public static void SetDefaultProps(){
Properties prop = new Properties();
OutputStream output = null;
try {
output = new FileOutputStream("./build/classes/configuracion.properties");
// Set the database property
prop.setProperty("url", "jdbc:mysql://192.168.1.192:3306/ordenestaller");
// Save Properties
prop.store(output, null);
} catch (IOException io) {
io.printStackTrace();
} finally {
if (output != null) {
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
SetDefaultProps();
}
}
Hardcoding the db url in the java code is not a good coding practice.
I would recommend you to put those urls in a properties files and read them as and when required using a ResouceBundle.
you can have "information.properties" file somewhere in your classpath and the contents of that file can be
dbURL:jdbc:mysql://192.168.1.192:3306/ordenestaller
and now in your code you can get this using a ResourceBundle
ResourceBundle bundle = ResourceBundle.getBundle("information");
String dbURL= bundle.getString("dbURL");
This will have an added advantage that you will not need to recompile your java class again if DB URl is changed.
Hope it helps