problem with deleting files - java

private static void deletefile(String file) {
int fileName = 500;
int z;
String[] File = new String[fileName];
for (z = 0; z < fileName; z++) {
File f1 = new File(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc" + z
+ ".txt");
boolean success = f1.delete();
if (!success) {
System.out.println("Deletion failed.");
System.exit(0);
} else {
System.out.println("File deleted.");
}
}
}
public static void main(String[] args) throws IOException {
switch (args.length) {
case 0:
System.out.println("File has not mentioned.");
System.exit(0);
case 1:
deletefile(args[0]);
System.exit(0);
default:
System.out.println("Multiple files are not allow.");
System.exit(0);
hi, this is my code for attempting to delete a certain files in java. It prints out file has not mentioned.i was trying to delete a set of txt files in a certain folder. The program should continue with the next file once a file is missing. Can anyone point out my mistake ? thanks..

Apparently you did not pass any command line parameters to your program.
(Although even if you did, it is not used anywhere in deletefile() - your method attempts to delete a fixed set of files in a specific directory, and if any of these is missing or you don't have permissions to delete it, it exits with an error message.)

You have to specify the file name as command line argument when running your Java program.
java MyClass file_to_delete

You need to have some check or catch exception when you create a new file so it wont stop when the file is not found.

Related

How to prevent the Path Traversal in Java

Recently, I used the AppScan Source to scan the coding, and it found out one of the finding which I don't know how to fix and pass to the scanner
Here's my code.
public void init()
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");
String pth = "C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF";
String n= prefix+file;
File fileExists = new File(n);
if (fileExists.exists()) {
PropertyConfigurator.configure("C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF" + file);
} else {
BasicConfigurator.configure();
}
}
I tried to add the if statement to check any special character in the path. However the scanner still report the finding in "File fileExists = new File(n);"
public void init()
{
String prefix = getServletContext().getRealPath("/");
String file = getInitParameter("log4j-init-file");
String pth = "C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF";
String n= prefix+file;
//For Security Checking
if (file != null && !n.contains("../") && !n.contains("$") && !n.contains("*"))//Check the path whether it's included risk character
{
File fileExists = new File(n);
if (fileExists.exists()) {
PropertyConfigurator.configure("C:\\wls1034\\user_projects\\domains\\base_domain\\servers\\AdminServer\\tmp\\_WL_user\\SimulationService\\39m5yi\\war\\WEB-INF" + file);
} else {
BasicConfigurator.configure();
}
}
}
This is just a false positive by the scanner. There is no security risk with the above code as no user input involved in reading or writing to the path.
The scanner flags file paths with variables.
var sr = new StreamReader("C:\\....\\WEB-INF" + file);
As mentioned by Ahmad, it is usually a false positive. But it is a good idea to verify a malicious user could not exploit the code and to get access to files that was not intended.
To make the scanner happy, you could supply it with hard coded paths, or create a switch statement for every possible file path.
switch (fileId)
{
case "1":
sr = new StreamReader("C:\file-1");
break;
case "2":
sr = new StreamReader("C:\file-2");
break;
}
But who wants to do that!
Your best option is to ensure no threat exists and to convince the security folks to allow your code to proceed.

Creating a simple data output file in Java

I am trying to write a simple data output file. When I execute the code I get a "No file exist" as the output and no data.txt file is created in the dir.
What am I missing? The odd thing is that it was working fine the other night, but when I loaded it up today to test it out again, this happened.
Here is the code:
import java.io.*;
import java.util.*;
public class DataStreams {
public static void main(String[] args) throws IOException {
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream("C:\\data.txt"));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}
}
The data file should be a simple display of numbers 1 through 9.
Thanks for your input.
On Windows platforms, C:\ is a restricted path by default. Previously the application may have been run as administrator allowing access.
Solution: Use a different location
DataOutputStream out =
new DataOutputStream(new FileOutputStream("C:/temp/data.txt"));
Create a text file named data.txt in c: .You must have deleted the file. Creating that file manually will work
You should have a look at the exception itself:
System.out.println("No file exist");
System.out.println(ex.getMessage());
Perhaps you have not the necessary rights, to access C:\ with your program.
To write data into a file, you should first create it, or, check if it exists.Otherwise, an IOException will be raised.
Writing in C:\ is denied by default, so in your case even if you created the file you will get an IOException with an Access denied message.
public static void main(String[] args) throws IOException {
File output = new File("data.txt");
if(!output.exists()) output.createNewFile();
try {
DataOutputStream out = new DataOutputStream(new FileOutputStream(output));
for (int i = 0; i < 10; i++) {
out.write(i);
}
} catch (IOException ioe) {
System.out.println("No file exist");
}
}

Open file to view its content [duplicate]

This question already has answers here:
How to open a file with the default associated program
(4 answers)
Closed 9 years ago.
I have a files list. Lets say it looks:
String[] lst = new String[] {
"C:\\Folder\\file.txt",
"C:\\Another folder\\another file.pdf"
};
I need some method to open these files with default program for them, lets say "file.txt" with Notepad, "another file.pdf" with AdobeReader and so on.
Does anyone knows how?
There is a method to do this:
java.awt.Desktop.getDesktop().open(file);
JavaDoc:
Launches the associated application to open the file.
If the specified file is a directory, the file manager of the current platform is launched to open it.
The Desktop class allows a Java application to launch associated applications registered on the native desktop to handle a URI or a file.
If you are using J2SE 1.4 o Java SE 5, the best option is:
for(int i = 0; i < lst.length; i++) {
String path = lst[i];
if (path.indexOf(' ') > 0) {
// Path with spaces
Runtime.getRuntime().exec("explorer \"" + lst[i] + "\"");
} else {
// Path without spaces
Runtime.getRuntime().exec("explorer " + lst[i]);
}
}
Just make sure the file is in the right location, and this should work fine.
try
{
File dir = new File(System.getenv("APPDATA"), "data");
if (!dir.exists()) dir.mkdirs();
File file = new File(dir"file.txt");
if (!file.exists()) System.out.println("File doesn't exist");
else Desktop.getDesktop().open(file);
} catch (Exception e)
{
e.printStackTrace();
}
I didn't know you have a String array now. So, this one uses regex to process the file list in the format you specified before. Ignore if not required.
If the file list is huge and you would prefer that the files open one by one cmd works great. If you want them to open all at once use explorer. Works only on Windows but then on almost all JVM versions. So, there's a trade-off to consider here.
public class FilesOpenWith {
static String listOfFiles = "{\"C:\\Setup.log\", \"C:\\Users\\XYZ\\Documents\\Downloads\\A B C.pdf\"}";
public static void main(String[] args) {
if (args != null && args.length == 1) {
if (args[0].matches("{\"[^\"]+\"(,\\s?\"[^\"]+\")*}")) {
listOfFiles = args[0];
} else {
usage();
return;
}
}
openFiles();
}
private static void openFiles() {
Matcher m = Pattern.compile("\"([^\"]+)\"").matcher(listOfFiles);
while (m.find()) {
try {
Runtime.getRuntime().exec("cmd /c \"" + m.group(1) + "\"");
// Runtime.getRuntime().exec("explorer \"" + m.group(1) + "\"");
} catch (IOException e) {
System.out.println("Bad Input: " + e.getMessage());
e.printStackTrace(System.err);
}
}
}
private static void usage() {
System.out.println("Input filelist format = {\"file1\", \"file2\", ...}");
}
}

No such file or directory error on a mac

I'm trying to read a file that exists in the following location of my Eclipse java project:
Tester -> src -> threads -> ReadFile.java
This is the code used:
public class Tester {
public static void main(String[] args) {
ReadFile[] readers;
readers = new ReadFile[3];
for (int intLoopCounter = 0; intLoopCounter < 3; intLoopCounter++) {
readers[intLoopCounter] =
new ReadFile("ReadFile.java", intLoopCounter);
System.out.println("Doing thread number: " + (intLoopCounter + 1));
}
}
Can you tell me what to add to:
new ReadFile("ReadFile.java"
so the file can be read?
There is a buffered reader in the ReadFile.java class file. I'm experimenting with this just to see if I can read the ReafFile.java file and show the results to the console.
Here is the code that is throwing the error from ReadFile.java:
public ReadFile(String filename, int i) {
id = i;
try {
input = new BufferedReader(new FileReader(filename));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Problem occured: " + e.getMessage());
} // catch
} // Constructor
Assuming that Tester is your project root directory, your path to the file should be "src/threads/ReadFile.java". If the file trully exists it will be found.
You need to modify the path in the call to ReadFile to include a full path, a path anchored by your user directory, or a path relative to the directory in which Eclipse runs your test program.
For example, if your project is located in /Users/myuser/projects/Tester/src/threads, you can use this line:
new ReadFile("/Users/myuser/projects/Tester/src/threads/ReadFile.java", intLoopCounter)

Exception when trying to start a program when a file already exists

I have an application that writes text to a File. If the File doesn't exist, it is created.
When I run the application for the first time, it all works correctly and the File is created. However, every subsequent time causes the application to crash. Could you please help explain why it doesn't work more than once.
My code is as follows...
public class Apples {
Formatter x;
File file = new File("myfile.txt");
public Apples() {
if (!file.exists()) {
try {
x = new Formatter("myfile.txt");
}
catch (Exception e) {
System.out.println("There was an error creating the file");
}
System.out.println("The file was created");
}
else {
System.out.println("The file already exists");
}
x.format("%s", "text");
x.close();
}
public static void main(String[] args) throws FileNotFoundException {
Apples a = new Apples();
}
}
I suspect that the problem is a NullPointerException on the line x.format("%s", "text"); because you aren't assigning a value to x if the file already exists.
Second time x is null because you don't init it.

Categories

Resources