How do I backup / restore any kind of databases inside my java application to flate files.Are there any tools framework available to backup database to flat file like CSV, XML, or secure encrypted file, or restore from csv or xml files to databases, it should be also capable of dumping table vise restore and backup also.
There are many ways to do this. It really depends on how complicated your "database" is.
The simplest solution is to write to a text file in a CSV format:
import java.io.PrintWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
public class FileOutput {
public static void main(String[] args) {
File file = new File("C:\\MyFile.csv");
FileOutputStream fis = null;
PrintWriter output = null;
try {
fos = new FileOutputStream(file);
output = new PrintWriter(fos);
output.println("Column A, Column B, Column C");
// dispose all the resources after using them.
outputStream.flush();
fos.close();
outputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Or, if you're looking for an XML solution, you can play with Xerces API, which I think is included in the latest JDK, so you just have to include the packages.
Related
I am unable to read the properties from the file . When I try to print it gives me null, When I debugged I understood it is not loading the file in function
pro.Load(). However my path is correct, still I am unable to load the file
package AdvancedJava;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;
public class ReadingPropertiesFile {
public static void main(String[] args) throws FileNotFoundException {
Properties pro = new Properties();
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
// BufferedReader reader = new BufferedReader(new FileReader(path));
File f = new File(path);
FileInputStream fis = null;
try {
fis = new FileInputStream(f);
pro.load(fis);
}
catch (IOException e) {
System.out.println(e.getMessage());
}
System.out.println(pro.getProperty("lastname"));
}
}
Properties file contents
firstname = John
lastname = harry
Automation = Selenium
I think the problem is in path:
String path = "C://Users//310259741//Documents//ProjectManagment//JavaBasics//object.properties";
should be like this:
String path = "C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
Also make sure you have a correct path to your properties file. If it is inside your project, the path should be like this:
String path = "C:\\...\\ProjectFolder\\src\\main\\resources\\object.properties";
Your example works fine for me. Without a stacktrace though, we won't be able to help you regarding the NPE you're getting.
In any way though, I couple of hints regarding your code. I would suggest using a try - with resources when operating with the FileInputStream to make sure that the resource is going to be closed once done.
You can avoid using new File(path);. Instead I would suggest using Paths from the java.nio.* package. An example of this based on your code snippet would be the following:
public static void main(String[] args) {
Properties properties = new Properties();
try (FileInputStream stream = new FileInputStream(Paths.get("E:\\test\\file.txt").toFile())) {
properties.load(stream);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(properties.getProperty("lastname"));
}
The advantage of using Paths is that they're (if not mistaken) system agnostic meaning that you won't need to worry about providing the proper path delimiters.
Actually, path should be with another separator
"C:\\Users\\310259741\\Documents\\ProjectManagment\\JavaBasics\\object.properties";
but what I should suggest you - it's to store your app properties files under your resource folder, kinda:
src/main/resources/config.properties
than you gonna be able to access this file like this:
public Properties extractFrom(String fileName) {
Properties properties = new Properties();
try (InputStream inputStream = PropertiesExtractor.class
.getClassLoader().getResourceAsStream(fileName)) {
properties.load(inputStream);
} catch (IOException ex) {
throw new RuntimeException("Cannot load properties", ex);
}
return properties;
}
extractFrom("config.properties");
I have a file, let's say C:\source.dat. I want to compress it into a zip file C:\folder\destination.zip.
I can't find a straightforward example, and the HelloWorld provided with the Maven project doesn't really apply in my case because I'm not writing a plaintext file, so hopefully someone can enlighten me on this.
For reference, the code provided in the example:
#Override
protected int work(String[] args) throws IOException {
// By default, ZIP files use character set IBM437 to encode entry names
// whereas JAR files use UTF-8.
// This can be changed by configuring the respective archive driver,
// see Javadoc for TApplication.setup().
final Writer writer = new TFileWriter(
new TFile("archive.zip/dir/HälloWörld.txt"));
try {
writer.write("Hello world!\n");
} finally {
writer.close();
}
return 0;
}
It's as simple as this:
new TFile("source.dat").cp(new TFile("destination.zip/source.dat"));
For more information, please refer to the Javadoc for the TFile class at http://truezip.java.net/apidocs/de/schlichtherle/truezip/file/TFile.html .
You may also want to try the TrueZIP Archetype File*, which is introduced at http://truezip.java.net/kick-start/index.html . The archetype generates many sample programs which you should explore to get a feel for the API.
This is a straight forward thing to do.
Use
1.ZipOutputStream -- This Class of java This class implements an output stream filter for writing files in the ZIP file format. Includes support for both compressed and uncompressed entries.
Offical Docs
http://docs.oracle.com/javase/6/docs/api/java/util/zip/ZipOutputStream.html
2.ZipEntry -- This This class is used to represent a ZIP file entry.
http://docs.oracle.com/javase/1.5.0/docs/api/java/util/zip/ZipEntry.html
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
public class ConverToZip {
public static void main(String[] args) {
// Take a buffer
byte[] buffer = new byte[1024];
try {
// Create object of FileOutputStream
FileOutputStream fos = new FileOutputStream("C:\\folder\\destination.zip.");
// Get ZipOutstreamObject Object
ZipOutputStream zos = new ZipOutputStream(fos);
ZipEntry ze = new ZipEntry("source.dat");
zos.putNextEntry(ze);
FileInputStream in = new FileInputStream("C:\\source.dat");
int len;
while ((len = in .read(buffer)) > 0) {
zos.write(buffer, 0, len);
}
in .close();
zos.closeEntry();
//remember close it
zos.close();
System.out.println("Done");
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I'm write some text a file then delete it, but the deletion is failed.
The code is very simple:
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
public class TestFile {
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
public static void writeFile(File file, String content) throws IOException {
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
}
}
The output is:
Deleted? false
And there is a file abc.txt contains hello still there under c:.
Then I use FileUtils.writeStringToFile(...) from commons-io.jar instead, the file will be deleted.
But I don't know where is wrong with my code, please help me to find it out.
You are only closing the file if you get an IOException.
Change it to a finally block and you will be able to close and delete the file.
public static void writeFile(File file, String content) throws IOException {
OutputStream out = new FileOutputStream(file);
try {
out.write(content.getBytes("UTF-8"));
} finally {
try {
out.close();
} catch (IOException ignored) {
}
}
}
You need to close your OutputStream when you finished writing the file.
try {
out = new FileOutputStream(file);
out.write(content.getBytes("UTF-8"));
out.close();
} catch (IOException e) {
try {
out.close();
} catch (IOException e1) {
// ignored
}
}
In your main method,
public static void main(String[] args) throws IOException {
File file = new File("c:\\abc.txt");
writeFile(file, "hello");
// delete the file
boolean deleted = file.delete();
System.out.println("Deleted? " + deleted);
}
You open the file, write to it and then do not close it. Java keeps the file open for you, so if you wanted to add more information to it, you could. However, to be able to delete the file, you need to make sure no other reference is open to it. You can do this by using file.close() to close the file handle Java reserves for you.
It's best practice to always close a stream when you are done with it, especially if you added data to it. Otherwise, you might run into situations where you are keepings files open by accident, or, in extreme cases, lose data you thought was saved already.
Have a look at what FileUtils.writeStringToFile() does that you haven't.
public static void writeStringToFile(File file, String data, String encoding) throws IOException {
OutputStream out = new java.io.FileOutputStream(file);
try {
out.write(data.getBytes(encoding));
} finally {
IOUtils.closeQuietly(out);
}
}
You will note that the out stream is always closed, wheras in your example it only gets closed in your catch block if the write() throws an exception.
On Windows, files that are open by any program cannot be deleted.
You just delete your file if an exception occurs. You need to do that every time, after you opened the file.
You may want to put close into a finally block.
If you're using Java 7 I consider using a try-with-ressources block, which takes care of closing files for you.
try (BufferedReader br = new BufferedReader(new FileReader(path)))
{
return br.readLine();
}
I have a file I'm using to hold system information that my program needs on execution.
The program will read from it and write to it periodically. How do I do this? Among other problems, I'm having trouble with paths
Example
How do I read/write to this properites file if deploying application as runnable jar
Take a look at the http://docs.oracle.com/javase/6/docs/api/java/util/Properties.html
You can utilize this class to use your key=value pairs in the property/config file
Second part of your question, how to build a runnable jar. I'd do that with maven, take a look at this :
How can I create an executable JAR with dependencies using Maven?
and this :
http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html
I see you're not using maven to build your project altogether
You can't write to a file that exists as part of a ZIP file... it does not exist as a file on the filesystem.
Considered the Preferences API?
To read from a file you can declare a file reader using a scanner as
Scanner diskReader = new Scanner(new File("myProp.properties"));
After then for example if you want to read a boolean value from the properties file use
boolean Example = diskReader.nextBoolean();
If you wan't to write to a file it's a bit more complicated but this is how I do it:
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;
public class UpdateAFile {
static Random random = new Random();
static int numberValue = random.nextInt(100);
public static void main(String[] args) {
File file = new File("myFile.txt");
BufferedWriter writer = null;
Scanner diskScanner = null;
try {
writer = new BufferedWriter(new FileWriter(file, true));
} catch (IOException e) {
e.printStackTrace();
}
try {
diskScanner = new Scanner(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
appendTo(writer, Integer.valueOf(numberValue).toString());
int otherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(otherValue + 10).toString());
int yetAnotherValue = diskScanner.nextInt();
appendTo(writer, Integer.valueOf(yetAnotherValue * 10).toString());
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static void appendTo(BufferedWriter writer, String string) {
try {
writer.write(string);
writer.newLine();
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
And then write to the file by:
diskWriter.write("BlahBlahBlah");
I have to, quote on quote,
1.Save accounts to a binary (serialized) file.
2.Load (recreate) accounts from a binary (serialized) file.
So firstly, I was looking up examples of what exactly that is and I am lost, in same scenarios people mention xml, in my head I think it means like 01010011000 (binary), and when I look at other code it looks like a normal text file save.
What exactly does he mean, and can someone post an example, or give me a site that better clarifies this?
Once I see what I actually need to do, I can implement it easily, I'm just confused on what exactly is being saved (data-wise) and how.
*I already have an option to save via textfile (.txt) if I can just use some of that code for this binary part.
Thanks!
Here is what I have now, it's still not working I think.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
public class SerializationMain implements Serializable {
public static void saveSerialized(Object YourObject, String filePath) throws IOException {
ObjectOutputStream outputStream = null;
try {
outputStream = new ObjectOutputStream(new FileOutputStream(filePath + ".dat"));
outputStream.writeObject(YourObject);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static Object loadSerialized(String filePath, Object[][] data1) throws IOException {
try {
FileInputStream fileIn = new FileInputStream(filePath);
ObjectInputStream in = new ObjectInputStream(fileIn);
try {
data1 = (Object[][]) in.readObject();
} catch (ClassNotFoundException ex) {
Logger.getLogger(SerializationMain.class.getName()).log(Level.SEVERE, null, ex);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
}
System.out.println(data1.length);
return data1;
}
}
Assuming you have a class called "account" you simply need to implements Serializable at the top of your class header.
From my understanding, that will serialize all the data into a binary form. You will need to of course still perform the steps to actually write/read the class object out to a file using ObjectOutputStream/ObjectInputStream.
So for example...
public class account implements Serializable
{ ...
}
Then in your main function for example, where you want to save the object, you would create a File, attach it to an ObjectOutputStream and write out your object in binary form.
First hit on google: http://www.javacoffeebreak.com/articles/serialization/index.html - basically you should serialize your object to a file. Then you can load it into an object again later.