The system cannot find the path specified with FileWriter - java

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();

Related

File.delete() isn't deleting the .Json file in Java

I am trying to delete a json file I just created, The file is in the same directory as the workplace so I didn't include it when creating the new File object.
I also closed the output stream before trying to delete the file by using .close() method.
import java.io.File;
public static void processFilesForValidation(String name, Scanner obj, PrintWriter logFile) {
int count = 0;
PrintWriter outputStream = null;
String[] line = obj.nextLine().split(",", -1);
if (count == 0) {
for (int i = 0; i < line.length; i++) {
try {
if (line[i].equals(" ")) {
throw new CSVFileInvalidException();
} else {
try {
outputStream = new PrintWriter((new FileOutputStream(name + ".json", true)));
} catch (FileNotFoundException e) {
System.out.println("Could not create json file " + name
+ ". Program will terminate after deleting any corrupted files and closing any opened files.");
obj.close();
outputStream.close();
String fname = name + ".json";
File file = new File(fname);
file.delete();
System.exit(0);
}
}
} catch (CSVFileInvalidException eCsvFileInvalidException) {
System.out.println(
"File " + name + ".CSV is invlaid: field is missing. \nFile is not converted to JSON.");
int detected = line.length - 1;
logFile.println("\nFile " + name + ".CSV is invalid. \nMissing field:" + detected
+ " detected, 1 missing");
for (int j = 0; j < line.length; j++) {
if (line[j].equals(" ")) {
logFile.print(line[j] + "***, ");
} else {
logFile.print(line[j] + ", ");
}
}
logFile.close();
outputStream.close();
String fname= name+".JSON";
File file = new File(fname);
file.delete();
break;
}
}
}
}
The code is a little long but this is the method, I hope you can help me.
You open a new outputStream every time around the loop. As far as I can tell, you only close it on a couple of errors. So, on loop #2, the first outputStream is left dangling and not closed.

Java Get Zip file content

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.

File not found error while uploading image file from client to server

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

how to output file lists to text file using java

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.

Java Having trouble saving file

I am trying to have my program save, but whenever I try to save a program that exists (so the second run through) it creates the temp, but it does not overwrite the old file.
Here is the code. Can anyone find out why it does not overwrite the old file with the new?
public static void saveBallotData(int i)throws IOException{
PrintWriter outputFile;
outputFile = new PrintWriter("temp2.txt");
File tempCheck = new File (list.get(i).getBallotNumber()+".txt");
if(tempCheck.exists()){
Scanner inputFile = new Scanner(tempCheck);
for(int m = 0; m < list.get(i).getNumberOfChoices(); m++){
if(list.get(i).getVote().equals(list.get(i).getChoice(m))){
//outputFile.println(list.get(i).getChoice(m) + ":" + getInt(m, tempCheck) + 1);
inputFile.nextLine();
}
else{
outputFile.println(inputFile.nextLine());
}
}
}
else{
for(int a = 0; a < list.get(i).getNumberOfChoices(); a++){
if(list.get(i).getVote().equals(list.get(i).getChoice(a))){
outputFile.println(list.get(i).getChoice(a) + ":" + "1");
}
else{
outputFile.println(list.get(i).getChoice(a) + ":" + "0");
}
}
}
System.out.println("PHE");
outputFile.close();
File g = new File("temp2.txt");
File f = tempCheck;
f.delete();
g.renameTo(f);
}

Categories

Resources