I have a Java class to write/append into existing properties file. After appending, it's replacing all single backslash with double backslash and it places single backslash before every semicolon.
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out= response.getWriter();
String systemPath=request.getParameter("SYSTEMPATH");
String deployPath = getServletConfig().getServletContext().getRealPath("/WEB-INF/DB.properties");
InputStream stream = getServletContext().getResourceAsStream("/WEB-INF/DB.properties");
Properties prop = new Properties();
prop.load(stream);
prop.setProperty("Workspace", systemPath);
File file = new File(deployPath);
FileOutputStream fileOut = new FileOutputStream(file);
prop.store(fileOut, "sample properties");
fileOut.close();
}
Before appending:
Url=jdbc:oracle:thin:#//192.168.1.22:1521/
Workspace=D:\RACHEL\SW\Antivirus
after appending:
Url=jdbc:oracle:thin:#//192.168.1.22:1521/
Workspace=D:\\RACHEL\\SW\\Antivirus
How to remove these extra backslashes?
The properties file should have the extra backslashes to start with. In particular, without them you could end up with the wrong data, e.g. if you have d:\foo\new that wouldn't mean what you expect it to.
The backslashes escape characters which are sensitive in properties files, basically. The colons are unnecessary (as they're not in the key) but they don't do any harm either. The doubling of backslashes for text is entirely beneficial.
This is documented in the Properties documentation - in particular, look at the store() method that you're calling.
Properties file has their own format. Colon and backslashes are special characters in properties file. So, they have to be escaped. Also take a look at Properties.load() documentation.
If you are using Properties class to write and read the file, there won't be any problem. But, if you write the properties file using Property class, and read using some other method, then you would have to handle the escapes manually.
you can retrieve the key and its value and check and it will not vary but in properties file
It seems to look with extra slashes
I had this same problem, as I was on stackoverflow on another issue. I remember had this code!
I hope it helps, at least it is java, but it does escaping an issue in Properties file backslash and semicolon pitfall.
// load to store prop
#SuppressWarnings ( "resource" )
PrintWriter pw = new PrintWriter( configFile );
pw.println( "#" + LocalDateTime.now() );
pw.println( "hibernate.connection.username=" + prop.getProperty( "hibernate.connection.username" ) );
pw.println( "hibernate.connection.password=" + prop.getProperty( "hibernate.connection.password" ) );
pw.println( "hibernate.connection.url=" + prop.getProperty( "hibernate.connection.url" ) );
pw.close();
Related
Is there a more elegant way to do the following?
try (FileWriter myWriter = new FileWriter(Paths.get(folder,fileName).toAbsolutePath().toString())){
I have folder path and filename as string and I want to safely combine them. For example if
String folder = "/tmp/"
String fileName = "/myfile.txt"
to not end up with
"/tmp//myfile.txt"
or with
String folder = "/tmp"
String fileName = "myfile.txt"
to not end up with
"/tmpmyfile.txt"
The way I am using is transforming String to path and back to String which feels weird, but it looks like FileWriter does not accept Path directly.
Is there some more elegant solution than the one I have?
Use Files.newBufferedWriter(Path, OpenOption...).
try (Writer myWriter = Files.newBufferedWriter(Paths.get(folder, fileName))) {
// other code
}
Note that, while the FileWriter constructor uses the JVM's default encoding, this method uses the UTF-8 encoding, which is considered generally more useful. If you need to replicate the behavior of the FileWriter constructor, use
Files.newBufferedWriter(path, Charset.defaultCharset());
I have the following code:
FileSystem fs = FileSystem.get(context.getConfiguration());
Path filePath2 = Path.mergePaths(outputPath, new Path( "/SomeFile"));
BufferedWriter writer2 = new BufferedWriter(new OutputStreamWriter(fs.create(filePath2,true)));
writer2.write("Key: " + key.toString() + "\nValue: " + values.iterator().next().getSensCol().toString());
writer2.close();
I'm using the Hadoop library for some of these classes. After I execute it, I see the file is created but there is nothing inside it, any ideas why that might be?
There is not sufficient information for a proper diagnosis, but your code looks correct ... except (maybe) for the path. On a Linux system (at least) a normal user should not be able write a file into the "/" directory.
So, I can suggest a couple of possible explanations:
The file is being written, but not to the directory that you are looking at.
The file open is failing (or the writes are failing) but your application is squashing the exception ... in some code that you haven't shown us.
Ah! It looks like you are using org.apache.hadoop.fs.FileSystem ! (The java.nio.file version of the FileSystem class doesn't have a get method.)
I don't think this changes my answer, apart for the stuff about being able to write to the "/" directory. That could be permissible for a Hadoop FS.
Use a FileWriter together with the BufferedWriter.
Path filePath2 = Path.mergePaths(outputPath, new Path( "/SomeFile"));
FileWriter fileWriter2 = null;
BufferedWriter writer2 = null;
try {
fileWriter2 = new FileWriter( filePath2.toFile() );
writer2 = new BufferedWriter( writer2 );
writer2.write("Key: " + key.toString() );
//if you are going to use an Iterator, you better actually use it.
for ( Iterator iterator = col.iterator() ; iterator.hasNext() ; ) {
writer2.write( "\nValue: " + iterator.next()
.getSensCol().toString() );
}
}
catch ( IOException ex ) {
//Exception handling
}
finally {
writer2.close();
fileWriter2.close();
}
I hope I have helped.
Have a nice day. :)
boolean valid = false;
String user = txtUser.getText();
String pass = txtPass.getText();
try {
PrintWriter writer = new PrintWriter("src/file");
writer.println("The line");
writer.println(user + "#" + pass);
JOptionPane.showMessageDialog(null,"Sign Up"complete",JOptionPane.INFORMATION_MESSAGE);
writer.close();
} catch(Exception e) {
}
I am making a sign up page and I already have made the login page. The # in the code is used to separate the username to the password. Everything works fine but the problem with this is that every time I sign up it replaces the sign up information I gave the previous time. So if I signed up the first time with the username "greg" and the password "877" it works fine but then if I go on program again and sign up another user with a different username and password, it replaces the first username and pass. I need it to go to new line after every time someone signs up.
Wrap your file with a FileWriter first:
PrintWriter writer = new PrintWriter(new FileWriter("src/file", true));
Here's the description for the constructor of FileWriter(String, boolean):
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
Parameters
fileName - String The system-dependent filename.
append - boolean if true, then data will be written to the end of the file rather than the beginning
you are using public PrintWriter(File file) to write to the file
The javadoc says -
parameter specifies the file to use as the destination of this writer. If the file
exists then it will be truncated to zero size; otherwise, a new file will be created.
The output will be written to the file and is buffered.
So in your case you need to append text to the contents of the existing file so as Luiggi said FileWriter is your friend
FileWriter, a character stream to write characters to file. By default, it will
replace all the existing content with new content, however, when you specified a
true (boolean) value as the second argument in FileWriter constructor, it will keep
the existing content and append the new content in the end of the file.
try in this way
PrintWriter outputFile = new PrintWriter(new FileWriter("src/file", true));
In my spring project, one of my service classes has this method to save a file named database.properties in disk:
public void create_properties(String maquina, String usuario, String senha) {
System.out.println("create_properties");
Properties props = new Properties();
props.setProperty("jdbc.Classname", "org.postgresql.Driver");
props.setProperty("jdbc.url", "jdbc:postgresql://"+maquina+"/horario" );
props.setProperty("jdbc.user", usuario );
props.setProperty("jdbc.pass", senha );
props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.hbm2ddl.auto", "validate");
FileOutputStream fos;
try {
fos = new FileOutputStream( "database.properties" );
props.store( fos, "propriedades" );
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
My problem is that the property jdbc:url should be something like that:
jdbc:postgresql://localhost:5432/horario
But what is being saved is this:
jdbc\:postgresql\://localhost\:5432/horario
Anyone can tell me how to avoid this backslashes to be included?
It's doing exactly the right thing - you're saving a properties file, which escapes things like colons using backslashes. From the documentation for Properties.store:
Then every entry in this Properties table is written out, one per line. For each entry the key string is written, then an ASCII =, then the associated element string. For the key, all space characters are written with a preceding \ character. For the element, leading space characters, but not embedded or trailing space characters, are written with a preceding \ character. The key and element characters #, !, =, and : are written with a preceding backslash to ensure that they are properly loaded.
If you load the properties file in using Properties.load, you'll get the original string back in the Properties object.
If you don't want to store the value in a properties file, use a Writer and just write the string directly.
I am trying to create a back up file for an html file on a web server.
I want the backup to be in the same location as the existing file (it's a quick fix). I want to create the file using File file = new File(PathName);
public void backUpOldPage(String oldContent) throws IOException{
// this.uri is a class variable with the path of the file to be backed up
String fileName = new File(this.uri).getName();
String pathName = new File(this.uri).getPath();
System.out.println(pathName);
String bckPath = pathName+"\\"+bckName;
FileOutputStream fout;
try
{
// Open an output stream
fout = new FileOutputStream (bckFile);
fout.close();
}
// Catches any error conditions
catch (IOException e)
{
System.err.println ("Unable to write to file");
System.exit(-1);
}
}
But if instead I was to set bckPath like this, it will work.
String bckPath = "C://dev/server/tomcat6/webapps/sample-site/index_sdjf---sd.html";
I am working on Windows, not sure if that makes a difference.
The result of String bckPath = pathName+"\"+bckName;
is bckPath = C:\dev\server\tomcat6\webapps\sample-site\filename.html - this doesn't result in a new file.
Use File.pathSeparator, that way you dont need to worry what OS you are using.
Try to use File.getCanonicalPath() instead of plain getPath(). This helps if the orginal path is not fully specified.
Regarding slashes, / or \ or File.pathSeparator is not causing the problem, because they are all the same on Windows and Java. (And you do not define bckFile in your code, only bckPath. Also use getCanonicalPath() on the new created bckPath.)