Checking existing file empty or not in java - java

My code is listing .ncat files and printing them to screen. I want to print if there is no .ncat files in directory, it prints out " there is no .ncat files" How can i do that ?
enter code here
File f = null;
String[] paths;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths)
{
if(path.toLowerCase().endsWith(".ncat")){
System.out.println(path);
}
}
}catch(Exception e){
e.printStackTrace();
}

File has an exists() method. You can check
(new File(path)).exists()

An extremely simple and clear way is to just set a flag to indicate if a .ncat file has been found. If no .ncat was in the directory, the flag will remain false and the statement will be printed. Try the following:
File f = null;
String[] paths;
boolean fileFound = false;
try{
f = new File("C:/Users/BURAK NURÇİÇEK/workspace/cs 222");
paths = f.list();
for(String path:paths)
{
if(path.toLowerCase().endsWith(".ncat")){
System.out.println(path);
fileFound = true;
}
}
if (!fileFound) System.out.println("There are no .ncat files");
}catch(Exception e){
e.printStackTrace();
}

You can use the buffer reader class:
BufferedReader br = new BufferedReader(new FileReader("pathToFile"));
if (br.readLine() == null) {
System.out.println("File is empty");
}

Checking existing file empty or not in java
To check whether a file is empty:
if(new File(pathname).length() > 0)
To check whether a file exist:
if(new File(pathname).exists())
To check whether a file exist in a folder and all it sub-directories, you can recursively check through the folder.

int numberOfFiles = new File(path).listFiles().length;
if(numberOfFiles == 0) {
System.out.println("Empty Directory");
}

Related

How to rename a txt file using Java after copying contents from another txt file

I have created a program where there is a file called groups.txt. This file contains a list of names. To delete a group, it has to exist within the file. I used the Scanner method to search through each line for the name. If it contains the line, it sets val as 1. Which triggers the val == 1 condition. What I wanted to do during this block, is try to delete groupName from the groups.txt file. To do this, I created a new txt file called TempFile which copies all the names from groups.txt EXCEPT groupName. This file is then renamed to groups.txt and the old groups.txt file is deleted.
Everything works as intended, except the renaming. The temp.txt file still exists and the groups.txt file is unchanged. I checked the boolean success, and it always returns as false. Any ideas how to solve this?
if (method.equals("delete group")){
int val = 0;
String groupName = myClient.readLine();
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
val = 1;
}
}
if (val == 1){
try {
File groupFile = new File("groups.txt");
File tempFile = new File("temp.txt");
BufferedReader reader = new BufferedReader(new FileReader(groupFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
System.out.println(groupName);
while ((currentLine = reader.readLine()) != null){
String trimLine = currentLine.trim();
if (trimLine.equals(groupName)){
continue;
} else {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.close();
reader.close();
groupFile.delete();
boolean success = tempFile.renameTo("groups.txt");
} catch (IOException f){
System.err.println("File Not Found: " + f.getMessage());
} }
} catch (FileNotFoundException f){
System.err.println("File Not Found Exception: " + f.getMessage());
}
}
CODE BEFORE THE ABOVE:
if (command.equals("group")){
String method = myClient.readLine();
if (method.equals("create group")){
String groupName = myClient.readLine();
int val = 0;
try {
Scanner file = new Scanner(new File("groups.txt"));
while (file.hasNextLine()){
String line = file.nextLine();
if (line.indexOf(groupName) != -1){
Report.error("group name already exists, please pick another");
val = 1;
}
}
} catch (FileNotFoundException f){
System.err.println("File Not Found: " + f.getMessage());
}
if (val == 0){
try {
PrintWriter out = new PrintWriter(new FileWriter("groups.txt", true));
out.println(groupName);
out.close();
} catch (IOException e){
Report.error("IOException: " + e.getMessage());
}
}
In the second part of the code, this is where I originally update the groups.txt file. So every time the user adds a group, it updates the groups.txt file by adding the new groupName to the end of the file. First, I make sure the groupName doesn't already exist using Scanner. myClient is a BufferedReader which reads from another class which stores what the user types in the command line.
Also do not forget to close Scanner. First you should make delete() work and make sure you know your current working directory, and write your filepath relative to it. Check with:
File file = new File("abc.txt");
System.out.println(file.getAbsolutePath());
One thing might be unrelated, also check your environment because
In the Unix'esque O/S's you cannot renameTo() across file systems. This behavior is different than the Unix "mv" command. When crossing file systems mv does a copy and delete which is what you'll have to do if this is the case. The same thing would happen on Windows if you tried to renameTo a different drive, i.e. C: -> D:

How to open a txt file using the method getName()

File file = new File("C:/mydirectory/");
File[] files = file.listFiles();
for(File f: files){
System.out.println(f.getName());
f.getName() contains the name of the file but how can I open the file using f.getName() ;? Or please help me to open all the txt files using a loop.
if (f.getName().contains("name wanted")) {
FileInputStream fis = null;
try (fis = new FileInputStream(f);
// use the file input stream to read data
}
or to read lines from the file
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
// process the line.
}
}
To display the name of all files you can use recursion, to get contents see above
public void display(File f) {
File[] files = file.listFiles();
for(File f: files){
if (f.isDirectory()) {
display(f);
} else if (f.getName().contains("value")) {
System.out.println(f.getName());
}
}
and call this as display(new File("C:/mydirectory/")) from a main method.
you can 'display' your result using JOptionPane
File file = new File("C:/mydirectory/");
String result = "";
for (String fileName: file.listFiles()){
result = result+"\n";
}
JOptionPane.showMessageDialog(null, result);
JOptionPanegrants static access, so you won't need any instances, the first parameter is the parent frame, null is allowed. The second parameter is the message (here: a list of all files within C:/mydirectory/) you want to 'display' ...
For read the whole file to List<String> use Files.readAllLines(f.toPath()) or Files.newInputStream(f.toPath()) for opening stream.

Java rename not working

Here is my code
private void edit(String search_bookname) {
String current_bookname ="", current_ISBN = "", current_author = "", current_rating = "", record = "", comma = ",", current_status = "";
int flag1 = 0, flag2 = 0;
File file = new File("Book_data.txt");
try {
BufferedReader reader = new BufferedReader (new FileReader (file));
File f = new File("Book_data_copy.txt");
FileWriter create = new FileWriter(f);
PrintWriter y = new PrintWriter(create);
while(reader.ready())
{
record = reader.readLine();
StringTokenizer st = new StringTokenizer(record, ",");
while(st.hasMoreTokens()) {
current_bookname = st.nextToken();
current_author = st.nextToken();
current_ISBN = st.nextToken();
current_rating = st.nextToken();
current_status = st.nextToken();
flag2 = 0;
if (search_bookname.equals(current_bookname)) {
flag1 = 1;
flag2 = 1;
try {
y.print(current_bookname); y.print(comma);
y.print(current_author); y.print(comma);
y.print(current_ISBN); y.print(comma);
y.print(current_rating); y.print(comma);
y.println("Borrowed");
} catch(Exception e) {}
Thread.sleep(1000);
}
}
if(flag2==0) // All non-matching records shall only be written to file. Record to be deleted will not be written to new file
{
y.print(current_bookname); y.print(comma); //One record per line..... Each field in a record is seperated by COMMA (" , " )
y.print(current_author); y.print(comma);
y.print(current_ISBN); y.print(comma);
y.print(current_rating);y.print(comma);
y.println(current_status);
}
}
reader.close();
y.close();
create.close();
} catch (Exception e) {}
if(flag1==1) //Rename File ONLY when record has been found for Edit
{
File oldFileName = new File("Book_data_copy.txt");
File newFileName = new File("Book_data.txt");
System.out.println("File renamed .....................");
try
{
newFileName.delete(); oldFileName.renameTo(newFileName);
if (oldFileName.renameTo(newFileName))
System.out.println("File renamed successfull !");
else
System.out.println("File rename operation failed !");
Thread.sleep(1000);
} catch (Exception e) {}
}
}
The project is for a library system. I am relatively new to java and I use netbeans on windows 8.1. The code outputs rename operation failed. Almost exactly the same code for edit has been used before in the program and it worked.
Any suggestions or code corrections would be helpfu.
Thanks!
Your issue is with the below code section
oldFileName.renameTo(newFileName);
if (oldFileName.renameTo(newFileName))
you are trying to rename twice. The first might pass but the 2nd will definitely fail. Check if the original file was renamed. If any error is thrown pring the stack trace and add the trace to your post.
You are trying to rename oldFileName twice:
newFileName.delete(); oldFileName.renameTo(newFileName); // rename
if (oldFileName.renameTo(newFileName)) // rename again ?!
System.out.println("File renamed successfull !");
else
System.out.println("File rename operation failed !");
The second rename in the if() fails, because the file was renamed already in the line before.
There are any number of problems here, starting with ignoring exceptions; not closing the file in a finally block; and using Reader.ready() incorrectly.
This is 2015. Use java.nio.file!
final Path srcFile = Paths.get("Book_data.txt").toAbsolutePath();
final Path dstFile = srcFile.resolveSibling("Book_data_copy.txt");
try (
final BufferedReader reader = Files.newBufferedReader(srcFile, StandardCharsets.UTF_8);
final BufferedWriter writer = Files.newBufferedWriter(dstFile, StandardCharsets.UTF_8,
StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
final PrintWriter pw = new PrintWriter(writer);
) {
// work with reader and pw
}
if (flag1 == 1)
Files.move(dstFile, srcFile, StandardCopyOption.REPLACE_EXISTING,
StandardCopyOption.ATOMIC_MOVE);
If you did that from the start, not only would your resources have been closed safely (your code doesn't do that) but you would have gotten a meaningful exception as well (you are trying to rename twice; you would have had a NoSuchFileException on the second rename).
Relying on File is an error, and it has always been.

Why the file is not created

I'm creating a directory and then a file. The problem is that the directory is created but the File is not.
When I'm doing this I'm creating and it prints out that "Successfully created new file: and the name of the file.
Can anyone help understand why?
public class Main
{
public static void main(String[] args) throws IOException
{
Scanner reader = new Scanner (System.in);
boolean success = false;
GetFiles getFile = new GetFiles();
System.out.println("Enter path of directory to create");
String dir = reader.nextLine();
// Create a new directory in Java, if it doesn't exists
File directory = new File(dir);
if(directory.exists())
{
System.out.println("Directory already exists");
}
else
{
System.out.println("Directory not exists, creating now");
success = directory.mkdir();
if(success)
System.out.println("Successfuly created new directory");
else
System.out.println("Failed to create new directory");
}
// Creatning new file in Java, only if not exists
System.out.println("Enter file name to be created");
String filename = reader.nextLine();
File f = new File(filename);
if(f.exists())
{
System.out.println("File already exists");
}
else
{
System.out.println("No such file exists, creating now");
success = f.createNewFile();
if(success)
System.out.printf("Successfully created new file: : %s%n", f);
else
System.out.printf("Failed to create new file: %s%n", f);
}
reader.close();
getFile.getAllFiles(directory);
}
}
Your code is completely working. It actually creates the file. You can see the created file in your java project.
Just add this line of code and it will work as you wish.
filename = dir + "\\" + filename;
File f = new File(filename);
I think the best ways --> to change the below lines:
#1.
if(directory.exists())
to below
if (directory.exists() && directory.isDirectory())
#2.
File f = new File(filename);
if(f.exists())
to below
File f = new File(directory,filename);
if (f.exists() && f.isFile()) {

how to know invalid path to save the file in java

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

Categories

Resources