When I test the program within the class, it deletes temp.txt fine, but when I call it from another class, it fails to delete. Any help much appreciated! (ps- I haven't attached the class from which I'm calling it)
public class txtWriteReadDelete{
public static void deleteRecord(String filePath,String usernameDelete) {
String tempFile="temp.txt";
File oldFile=new File(filePath);
System.out.println("oldFile: "+ oldFile);
File newFile=new File(tempFile);
String username="";String password="";
try {
FileWriter fileWriter=new FileWriter(tempFile,true);
BufferedWriter bufferedWriter =new BufferedWriter(fileWriter);
PrintWriter printWriter=new PrintWriter(bufferedWriter);
Scanner x=new Scanner(new File(filePath));
x.useDelimiter("[,\n]");
while (x.hasNext()){
username=x.next();
password=x.next();
if(!username.equals(usernameDelete)) {
System.out.println(username);
printWriter.println(username + "," + password);
}
x.close();
printWriter.flush();
printWriter.close();
boolean deleted = oldFile.delete();
System.out.println("temp deleted: "+deleted);
File dump=new File(filePath);
newFile.renameTo(dump);
}
catch(Exception E) {
E.printStackTrace();
JOptionPane.showMessageDialog(null, "ERROR");
}
Deleting a file using .delete() operation expect a valid path. If the path is incorrect .delete() would not be able to delete the file.
You can check the validity of the file using oldFile.isFile() operation.
You need to provide the complete path of the file.
Related
I'm new to programming, every time I try to read a file. I get FileNOtFoundException.
Where could I be going wrong?
import java.io.*;
import java.util.Scanner;
public class ReadFile
{
public ReadFile()
{
readFile();
}
public void readFile()
{
String filename = "trees.txt";
System.out.println(new File(".").getAbsolutePath()); //file is at this path.
String name = "";
try
{
FileReader inputFile = new FileReader(filename);
Scanner parser = new Scanner(inputFile);
while (parser.hasNextLine())
{
name = parser.nextLine();
System.out.println(name);
}
inputFile.close();
}
catch (FileNotFoundException exception)
{
System.out.println(filename + " not found");
}
}
}
Is there any other way I could read the file?
this code
FileReader inputFile = new FileReader(filename);
You must define full path to file with name filename if not it will open file not at current working directory
you should try
FileReader inputFile = new FileReader(new File(new File("."), filename));
// defind new File(".") it mean you will you open file in current working directory
you can read more at: Java, reading a file from current directory?
Try printing the path of the file you are actually trying to open so you can be sure that the file exists in the right location
String filename = "trees.txt";
File file = new File(filename);
System.out.println(file.getAbsolutePath());
Also, you are closing the FileReader inside the try, and not closing the Scanner, if some error ever occurs those resources will never be closed, you need to put those close statements in a finally block, or better use try with resources
I have an application that creates a .txt file. I want to overwrite it. This is my function:
try{
String test = "Test string !";
File file = new File("src\\homeautomation\\data\\RoomData.txt");
// if file doesnt exists, then create it
if (!file.exists()) {
file.createNewFile();
}else{
}
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
What should I put in the else clause, if the file exists, so it can be overwritten?
You don't need to do anything particular in the else clause. You can actually open a file with a Writer with two different modes :
default mode, which overwrites the whole file
append mode (specified in the constructor by a boolean set to true) which appends the new data to the existing one
You don't need to do anything, the default behavior is to overwrite.
No clue why I was downvoted, seriously... this code will always overwrite the file
try{
String test = "Test string !";
File file = new File("output.txt");
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(test);
bw.close();
System.out.println("Done");
}catch(IOException e){
e.printStackTrace();
}
Just call file.delete() in your else block. That should delete the file, if that's what you want.
FileWriter(String fileName, boolean append)
Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written.
The Below one line code will help us to make the file empty.
FileUtils.write(new File("/your/file/path"), "")
The Below code will help us to delete the file .
try{
File file = new File("src\\homeautomation\\data\\RoomData.txt");
if(file.delete()){
System.out.println(file.getName() + " is deleted!");
}else{
System.out.println("Delete operation is failed.");
}
}catch(Exception e){
e.printStackTrace();
}
I have a question about writing csv file on the current project in eclipse
public static void Write_Result(String Amount_Time_Dalta) throws IOException{
File file;
FileOutputStream fop = null;
String content = "";
String All_Result[] = Amount_Time_Dalta.split("-");
String path ="/Users/Myname/Documents/workspace/ProjectHelper/"+All_Result[1] + ".csv";
System.out.println(path);
content = All_Result[3]+ "," + All_Result[5] + "\n";
System.out.println(content);
file = new File(path);
fop = new FileOutputStream(file);
file.getParentFile();
if (!file.exists()) {
file.createNewFile();
}
byte[] contentInBytes = content.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
}
and I am getting error which is
Exception in thread "main" java.io.FileNotFoundException: Invalid file path
at java.io.FileOutputStream.<init>(FileOutputStream.java:215)
at java.io.FileOutputStream.<init>(FileOutputStream.java:171)
at FileDistributor.Write_Result(FileDistributor.java:59)
at FileDistributor.main(FileDistributor.java:29)
I used
String path ="/Users/Myname/Documents/workspace/ProjectHelper/";
path to read a files. I was working fine.
However, when I am using same path to write result to file ( can be exist or not. I create or overwrite a file.) it returns Invalid file path.... I am not really sure why..
updated
just found interesting thing. when i just use File newTextFile = new File("1000".csv); then it is working. however, when i replace to File newTextFile = new File(filename +".csv"); it doesn't work.
What you have here is a valid path from which a File object can be created:
/Users/Myname/Documents/workspace/ProjectHelper/
But if you look at it a second time, you'll see that it refers to a directory, not a writable file. What's your file name?
What does your System.out.println say is the value of All_Result[1]?
Sample Code:
import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
public class Test
{
public static void main(String[] args)
{
String[] array = {"1000.csv", "800.csv", "700.csv"};
File file;
FileOutputStream fop;
// Uncomment these two lines
//String path = "c:\\" + array[0];
//file = new File(path);
// And comment these next two lines, and the code still works
String path = "c:\\";
file = new File (path + array[0]);
// Sanity check
System.out.println(path);
try
{
fop = new FileOutputStream(file);
}
catch(IOException e)
{
System.out.println("IOException opening output stream");
e.printStackTrace();
}
if (!file.exists())
{
try
{
file.createNewFile();
}
catch(IOException e)
{
System.out.println("IOException opening creating new file");
e.printStackTrace();
}
}
}
}
In order to get this code to break, instead of passing array[0] as a file name, just pass in an empty string "" and you can reproduce your error.
I have encountered the same problem and was looking for answer. I tried using string.trim() and put it into the outputstream and it worked. I am guessing there are some trailing characters or bits surrounding the file path
I am trying to copy a text file but when the code finishes executing I only have the last line of text in the file. Obviously the scanLine() keeps overwriting the same line but I cant figure out to solve this problem. Any ideas?
do{
try{
FileWriter name = new FileWriter("/home/fok/Desktop/out");
BufferedWriter out = new BufferedWriter(name);
a=x.nextLine();scanner x grabs next line and sets it string a
out.write(a);//writes a to file
out.close();//closees file
} catch (IOException ioe){
System.out.println("file writer error");
}
} while(x.hasNext());
It is pretty simple, you are closing and opening the file inside the for loop.
public void readfile(){
try {
FileWriter name = new FileWriter("/home/fok/Desktop/out");
BufferedWriter out = new BufferedWriter(name);
do {
a=x.nextLine();scanner x grabs next line and sets it string a
out.write(a);//writes a to file
} while(x.hasNext());
out.close();//closees file
} catch (IOException ioe){
System.out.println("file writer error");
}
}
In Java I want to create a file from and save the data on it. The File name with path is taken from user. Now if user give invalid path like C:\temp\./user\fir/st.csv which is an invalid path because "." and / are in the path and on windows operating system "\" is used as path separator.
Before executing the program(a command line tool), there was no temp folder in C:\ directory, but when I run the program it creates temp folder then in temp it creates user then in user it create fir folder and finally st.csv in it. While I want that if such type of invalid path or file name is given by the user user should be noticed by message "Invalid path or file name".
What should I do? Program code is like below:
public class FileTest {
public static void main(String args[]) {
try {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter path:");
String path = br.readLine();
File file = new File(path);
String path1 = file.getParent();
File file2 = new File(path1);
if (!file2.exists()) {
System.out.println("Directory does not exist , So creating directory");
file2.mkdirs();
}
if (!file2.exists()) {
System.out.println("Directory can not be created");
} else {
FileWriter writer = new FileWriter(file);
PrintWriter out = new PrintWriter(writer);
System.out.println("Please enter text to write on the file, print exit at new line to if finished");
String line = "";
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("exit")) {
System.out.println("Thanks for using our system");
System.exit(0);
} else {
out.println(line);
out.flush();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Now if I give the path as C:\tump\./user\fir/st.csv then it create tump folder in C drive , then user in tump, then fir in user folder then st.csv file in it.
boolean exists = (new File("filename")).exists();
if (exists) {
// File or directory exists
} else {
// File or directory does not exist
}
PLUS: You must never use hard-coded path separators. You're having problems by that, use instead the static attributes
File.separator - string with file separator
File.separatorChar - char with file separator
File.pathSeparator - string with path separator
File.pathSeparatorChar - char with path separator
Looks very similar to this:
Is there a way in Java to determine if a path is valid without attempting to create a file?
There's a link in one of the answers to here:
http://www.thekua.com/atwork/2008/09/javaiofile-setreadonly-and-canwrite-broken-on-windows/
Which details what could possibly work for you:
By Peter Tsenga
public static boolean canWrite(String path) {
File file = new File(path);
if (!file.canWrite()) {
return false;
}
/* Java lies on Windows */
try {
new FileOutputStream(file, true).close();
} catch (IOException e) {
LOGGER.info(path + ” is not writable: ” + e.getLocalizedMessage());
return false;
}
return true;
}
You mention this is a command line tool. Does that mean it will be always run from the command line, or could it be called from an environment that presumes no further user interaction (like batch file or by Ant)?
From a command line, it is possible to pop a JFileChooser. This is a much better way to accept a file name from the user. It is easier for the user, and more reliable for the program.
Here is an example based on your code:
import java.io.*;
import javax.swing.*;
public class FileTest {
public static void main(String args[]) {
SwingUtilities.invokeLater( new Runnable() {
public void run() {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showOpenDialog(null);
if (returnVal==JFileChooser.APPROVE_OPTION) {
File file = fileChooser.getSelectedFile();
try {
if (!file.getParentFile().exists()) {
System.out.println("Directory does not exist, creating..");
file.getParentFile().mkdirs();
}
if (!file.getParentFile().exists()) {
System.out.println("Directory can not be created");
} else {
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
FileWriter writer = new FileWriter(file);
PrintWriter out = new PrintWriter(writer);
System.out.println("Please enter text to write on the file," +
" print exit at new line to if finished");
String line = "";
while ((line = br.readLine()) != null) {
if (line.equalsIgnoreCase("exit")) {
System.out.println("Thanks for using our system");
System.exit(0);
} else {
out.println(line);
out.flush();
}
}
}
}
catch (IOException e) {
e.printStackTrace();
}
} else {
System.out.println("Maybe next time..");
}
}
});
}
}
Note that if I were coding this, I'd then go on to get rid of the InputStreamReader and instead show the text in a JTextArea inside a JFrame, JDialog or (easiest) JOptionPane, with a JButton to invoke saving the edited text. I mean, a command line based file editor? This is the 3rd millennium (damn it!).
In my case which I required this works
if(!path.equals(file.getCanonicalPath())){
System.out.println("FAILED:Either invalid filename, directory or volume label , syntax error");
System.exit(0);
}
By adding this code just after File file=new File(path); it will work fine and will notice the user if given path is incorrect
As there is only two options either java will create the file on some path which will be canonical path or if not able to create the file it will give exception. So if there is any mismatch in the path given by the user and canonical path then it means user type wrong path which java can not create on the file system, so we will notice the user, or if java give exception then we can catch it and will notice the user for incorrect path