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();
}
}
}
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");
String inXSL="src/main/resources/abc.xslt";
Here am trying to get the file from the path name and process it but the file is never getting recognized from the given path(JAVA).FYI,the system is MAC.
The file is located inside src/main/resources inside the project.
Please provide inputs on this.
When your application is packaged and built, your file will be placed within the class path of your jar (or war) along with the other classes. It should be loaded using a resource stream. Here is some sample code that would print the contents of the file by loading it from the classpath.
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
public class Test {
public static void main(String[] args) throws InterruptedException {
byte[] contents = new byte[1024];
InputStream inStream = Test.class.getClassLoader().getResourceAsStream("abc.xslt");
BufferedInputStream bis = new BufferedInputStream(inStream);
int bytesRead=0;
String strFileContents = null;
try {
while( (bytesRead = bis.read(contents)) != -1){
strFileContents = new String(contents, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(strFileContents);
}
}
The important line is:
InputStream inStream = Test.class.getClassLoader().getResourceAsStream("abc.xslt");
Depending on your usage, the input stream would be passed into whatever API you are using.
I'm trying to write a binary file to a specified folder, however it keeps giving me an exception.
For example, if I write the file without specifying any folder the program writes it with no problem:
public void saveFile(String name) throws IOException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(name + ".bin"));
out.writeObject(this);
out.close();
}
However, when I try to specify the folder the program just doesn't write the file:
public void saveFile(String name) throws IOException {
File location = new File("/path/" + name + ".bin");
FileOutputStream fos = new FileOutputStream(location);
ObjectOutputStream out = new ObjectOutputStream(fos);
out.writeObject(this);
out.close();
fos.close();
}
I tryed several different ways but still no solution.
Does anybody know what am I doing wrong?
Check if the class which you want to write is Serializable or not.
public class Foo implements java.io.Serializable{
//...
public void write() throws IOException{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("Test.bin"));
os.writeObject(this);
os.close();
}
}
Another problem:
If there is no folder named path it cannot write the object
Check your code again.
The Only reason seems for non Serialization is that u might not have implemented Serializable interface
and give your path name correctly for eg:-"C:\Users\.."
Hope it works
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");
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.