My problem is that I want to see if a file is in a zip file. So I have made this code :
File zipf = new File(backupFolder, dfws.format(new Date()) + ".zip");
if (!zipf.exists()) zipf.createNewFile();
fs = new FileOutputStream(zipf);
ZipOutputStream zos = new ZipOutputStream(fs);
System.out.println("size : " + zipf.length());
if (zipf.length() > 0) {
ZipFile zf = new ZipFile(zipf);
System.out.println("entry : " + zf.getEntry(name));
if (zf.getEntry(name) != null) {
int index = 1;
while (zf.getEntry(index + "_" + name) != null) {
index++;
}
name = index + "_" + name;
}
zf.close();
}
System.out.println("index found : " + name);
But the problem is that the length of the file is always 0. And I can't create an instance of ZipFile if the zip file doesn't have files inside.
Thanks to RealSkeptic : I had to open the FileOutputStream after creating the ZipFile.
Related
How in java code do i copy everything from src/main/resources directory inside of the jar file into the same directory of the jar file?
This is what i found from org.bukkit.plugin.java.JavaPlugin and it seems to work
public void saveResource(String resourcePath, boolean replace) {
if (resourcePath == null || resourcePath.equals("")) {
throw new IllegalArgumentException("ResourcePath cannot be null or empty");
}
resourcePath = resourcePath.replace('\\', '/');
InputStream in = getResource(resourcePath);
if (in == null) {
throw new IllegalArgumentException("The embedded resource '" + resourcePath + "' cannot be found");
}
File outFile = new File(dataFolder, resourcePath);
int lastIndex = resourcePath.lastIndexOf('/');
File outDir = new File(dataFolder, resourcePath.substring(0, lastIndex >= 0 ? lastIndex : 0));
if (!outDir.exists()) {
outDir.mkdirs();
}
try {
if (!outFile.exists() || replace) {
OutputStream out = new FileOutputStream(outFile);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.close();
in.close();
} else {
logger.log(Level.WARNING, "Could not save " + outFile.getName() + " to " + outFile + " because "
+ outFile.getName() + " already exists.");
}
} catch (IOException ex) {
logger.log(Level.SEVERE, "Could not save " + outFile.getName() + " to " + outFile, ex);
}
}
I'm currently trying to developp a simple software which retrieves articles on a nntp server. I'm using NNTPClient from apache.commons.net.
When I retrieve all the segments of an article, segments are longer than expected and I cannot decode them (and merrge them) with an yDec soft (like this one).
Here's my code which downloads segments and write them on the HDD :
BufferedReader br;
String line;
List<File> files = new ArrayList<File>();
for(NzbSegment s : segments) {
String str = s.getMessageID();
br = (BufferedReader) client.retrieveArticleBody("<" + str + ">");
String filePath = fileName + "-" + s.getSegmentNumber() +"body.yenc";
File f = new File(filePath);
f.delete(); //Make sure we have a new clean file
f = new File(filePath);
int bytes = 0;
while ((line = br.readLine()) != null) {
FileUtils.writeStringToFile(f,line + "\n",true);
bytes += line.getBytes().length;
}
System.out.println("size : " + s.getBytes() + " compare to : " + bytes);
br.close();
files.add(f);
}
with a POJO NzbSegment :
public class NzbSegment {
private int bytes;
private int segmentNumber;
private String messageID;}
Do you know where am I mistaken ?
I tried uploading an image file from client to server but I'm getting following error on server console:
java.io.FileNotFoundException: /usr/share/tomcat7/imageFolder/images/download_1412168176953.jpg (No such file or directory)
The code to do this is a follows :
String dirName = System.getProperty("user.home") + File.separator + "imageFolder" ;
File theDir = new File(dirName);
if (!theDir.exists()) {
if (!theDir.mkdirs()) {
if (!theDir.mkdir()) {
System.out.println("fail to create directory " + dirName);
}
}
}
dirName += File.separator + images;
theDir = new File(dirName);
if (!theDir.exists()) {
if (!theDir.mkdirs()) {
if (!theDir.mkdir()) {
System.out.println("fail to create directory " + dirName);
}
}
}
Long date = new Date().getTime();
fileName = dirName + File.separator + basename + "_" + date.toString() + "." + extname;
File f = new File(fileName);
OutputStream outputStream = new FileOutputStream(f);
outputStream.write(file.getBytes());
fileList.add(fileName);
Anyone plz help. Thanks in advance
hello i am a newbie to java. i just started learning java last week.
below is a code I am using to display all files and the corresponding file sizes of a folder and it's subfolder.
However, instead of displaying the output in the Eclipse console, what I need to achieve is actually output the same data to a text file. I've been searching on the net on how to accomplish this over the last couple of days but I wasn't able to come to a solution.
Can someone advise me on what code to use to accomplish my task?
Thanks so much!
public class ReadFile1 {
public static void main(String[] a)throws IOException{
showDir(1, new File("/Users/User/Documents/1 eclipse test/testfolder1"));
//File file = new File("/Users/User/Documents/1 eclipse test/testfolder1/puppy4.txt");
//long fileSize = file.length();
}
static void showDir(int indent, File file) throws IOException {
for (int i = 0; i < indent; i++)
System.out.print('-');
System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");
if (file.isDirectory()) {
File[] files = file.listFiles();
for (int i = 0; i < files.length; i++)
showDir(indent + 4, files[i]);
}
}
}
Here is your example converted :
public class ReadFile1
{
public static void main(String[] a) throws IOException
{
FileWriter fstream = new FileWriter("C:\\test.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
showDir(out,1,new File("C:\\"));
out.flush();
out.close();
}
static void showDir(BufferedWriter writer, int indent, File file) throws IOException
{
for(int i = 0; i < indent; i++)
{
writer.write('-');
//System.out.print('-');
}
writer.write(file.getName() + " - " + file.length() / 1024 + " KB");
writer.newLine();
//System.out.println(file.getName() + " - " + file.length() / 1024 + " KB");
if(file.isDirectory())
{
File[] files = file.listFiles();
for(int i = 0; i < files.length; i++)
{
showDir(writer,indent + 4, files[i]);
}
}
}
}
Update your showDir with the file writing code as mentioned here:
File file = new File("info.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}
PrintWriter writer = new PrintWriter(file);
writer.println(file.getName() + " - " + file.length() / 1024 + " KB");
writer.close();
This will put the console output into the text file:
try{
PrintStream out = new PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}catch(SecurityException se){
//Exception handling
}
setOut(PrintStream out) reassigns the "standard" output stream.It throws SecurityException -- if a security manager exists and its checkPermission method doesn't allow reassigning of the standard output stream.
I have this code:
private static void saveMetricsToCSV(String fileName, double[] metrics) {
try {
FileWriter fWriter = new FileWriter(
System.getProperty("user.dir") + "\\output\\" +
fileTimestamp + "_" + fileDBSize + "-" + fileName + ".csv"
);
BufferedWriter csvFile = new BufferedWriter(fWriter);
for(int i = 0; i < 4; i++) {
for(int j = 0; j < 5; j++) {
csvFile.write(String.format("%,10f;", metrics[i+j]));
}
csvFile.write(System.getProperty("line.separator"));
}
csvFile.close();
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
But I get this error:
C:\Users\Nazgulled\Documents\Workspace\Só
Amigos\output\1274715228419_5000-List-ImportDatabase.csv
(The system cannot find the path
specified)
Any idea why?
I'm using NetBeans on Windows 7 if it matters...
In general, a non existent file will be created by Java only if the parent directory exists.
You should check/create the directory tree:
String filenameFullNoPath = fileTimestamp + "_" + fileDBSize + "-"
+ fileName + ".csv";
File myFile = new File(System.getProperty("user.dir") + File.separator
+ "output" + File.separator + filenameFullNoPath);
File parentDir = myFile.getParentFile();
if(! parentDir.exists())
parentDir.mkdirs(); // create parent dir and ancestors if necessary
// FileWriter does not allow to specify charset, better use this:
Writer w = new OutputStreamWriter(new FileOutputStream(myFile),charset);
You can use getParentFile (Java Doc) to make sure that the parent directory exists. The following will check that the parent directory exists, and create it if it doesn't.
File myFile = new File(fileName);
if(!myFile.getParentFile.exists()) {
myFile.getParentFile.mkdirs();
}
I'd guess that the "output" directory doesn't exist. Try adding:
new File(System.getProperty("user.dir") + File.separator + "output").mkdir();