I'm trying to create a program that will go to specific director(ies) and print files that are located in there.
Here's the code:
import java.io.File;
public class FileViewer {
mport java.io.File;
public class FileViewer {
public void Srch(String path)
{
File root=new File(path);
File[] list=root.listFiles();
for(File x:list)
{
if(x.isDirectory())
{
Srch(x.getAbsolutePath());
System.out.println(x.getAbsolutePath());
}
else
{
System.out.println(x.getAbsolutePath());
}}}}
public class Viewer {
public static void main(String[] args) {
FileViewer Srch2=new FileViewer();
Srch2.Srch("Home\\Documents");
}
}
And I'm getting following error
Exception in thread "main" java.lang.NullPointerException
at FileViewer.Srch(FileViewer.java:9)
at Viewer.main(Viewer.java:7)
What seems to be the problem? Thanks
File.listFiles() may return null if it's used on an object is not a directory, or can't be accessed. I'm not sure whether "Home\\Documents" exists, but you should probably take a defensive approach in your method:
public void Srch(String path) {
File root=new File(path);
if (root.exist() && root.isDirectory()) {
File[] list=root.listFiles();
for(File x:list) {
Srch(x.getAbsolutePath());
System.out.println(x.getAbsolutePath());
}
} else {
System.out.println(x.getAbsolutePath());
}
}
The problem is most occurring because in your Srch method you call listFiles before checking whether the root is actually a directory. As stated in the javadoc of that method
Returns null if this abstract pathname does not denote a directory
Just make sure you handle that case as well. For example
public class FileViewer {
public void Srch(String path){
File root=new File(path);
File[] list=root.listFiles();
if ( list == null ){
return;
}
for(File x:list){
if(x.isDirectory()){
Srch(x.getAbsolutePath());
System.out.println(x.getAbsolutePath());
} else {
System.out.println(x.getAbsolutePath());
}
}
}
}
Note that a NullPointerException is one of the easiest exceptions to debug in Java. Just place a breakpoint with your debugger at the line indicated in the stacktrace and check which object is null. Then you know why you get the exception and you can start fixing it. Typically this boils down to:
null is a valid situation and you forgot to handle it
null was not a valid situation, and then you need to investigate how that variable could be null and fix it upstream
Sidenote for the next time you post a question:
Provide proper indentation for the code you post. Yours is really hard to read
Try to avoid copy-paste errors when pasting code. The first two lines are duplicated
You posted the stacktrace (good), but it would even be better if you indicated to which line the line number appearing in the stacktrace corresponds. Remember, we do not have access to your code so linking a line number from a stacktrace to the code snippet you post is far from trivial
A java.lang.NullPointerException appears, when Java wants to use something that isn't there. Could it be that the path is wrong?
Here :
File[] list=root.listFiles();
The method listFile may return "null".
Check for the Javadoc: http://docs.oracle.com/javase/6/docs/api/java/io/File.html#listFiles()
So then you do a foreach on this null variable, you get a NullPointerException if the pathname given to Srch method does not denote a directory.
if(list!=null)
{
for(File x:list)
{
if(x.isDirectory())
{
Srch(x.getAbsolutePath());
System.out.println(x.getAbsolutePath());
}
else
{
System.out.println(x.getAbsolutePath());
}
}
}
May be "Home\Documents" not exists, try with abslotute path.
Related
I'm trying to analyse some bits of Java-code, looking if the code is written too complexly. I start with a String containing the contents of a Java-class.
From there I want to retrieve, given a function-name, the "inner code" by that function. In this example:
public class testClass{
public int testFunction(char x) throws Exception{
if(x=='a'){
return 1;
}else if(x=='{'){
return 2;
}else{
return 3;
}
}
public int testFunctionTwo(int y){
return y;
}
}
I want to get, when I call String code = getcode("testFunction");, that code contains if(x=='a'){ ... return 3; }. I've made the input code extra ugly, to demonstrate some of the problems one might encounter when doing character-by-character-analysis (because of the else if, the curly brackets will no longer match, because of the Exception thrown, the function declaration is not of the form functionName{ //contents }, etc.)
Is there a solid way to get the contents of testFunction, or should I implement all problems described manually?
You need to a java parser. I worked too with QDox. it is easy to use. example here:
import com.thoughtworks.qdox.JavaProjectBuilder;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaMethod;
import java.io.File;
import java.io.IOException;
public class Parser {
public void parseFile() throws IOException {
File file = new File("/path/to/testClass.java");
JavaProjectBuilder builder = new JavaProjectBuilder();
builder.addSource(file);
for (JavaClass javaClass : builder.getClasses()) {
if (javaClass.getName().equals("testClass")) {
for (JavaMethod javaMethod : javaClass.getMethods()) {
if (javaMethod.getName().equals("testMethod")) {
System.out.println(javaMethod.getSourceCode());
}
}
}
}
}
}
Have you considered using a parser to read your code? There are a lot of parsers out there, the last time I worked on a problem like this http://qdox.codehaus.org made short work of these kinds of problems.
I am currently working on a method that will create files and directories. Bellow is the use case & problem explained.
1) When a user specifies a path e.g "/parent/sub folder/file.txt", the system should be able to create the directory along with the file.txt. (This one works)
2) When a user specifies a path e.g "/parent/sub-folder/" or "/parent/sub-folder", the system should be able to create all directories. (Does not work), Instead of it creating the "/sub-folder/" or /sub-folder" as a folder, it will create a file named "sub-folder".
Here is the code I have
Path path = Paths.get(rootDir+"test/hello/");
try {
Files.createDirectories(path.getParent());
if (!Files.isDirectory(path)) {
Files.createFile(path);
} else {
Files.createDirectory(path);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
You need to use createDirectories(Path) instead of createDirectory(path). As explained in the tutorial:
To create a directory several levels deep when one or more of the
parent directories might not yet exist, you can use the convenience
method, createDirectories(Path, FileAttribute). As with the
createDirectory(Path, FileAttribute) method, you can specify an
optional set of initial file attributes. The following code snippet
uses default attributes:
Files.createDirectories(Paths.get("foo/bar/test"));
The directories
are created, as needed, from the top down. In the foo/bar/test
example, if the foo directory does not exist, it is created. Next, the
bar directory is created, if needed, and, finally, the test directory
is created.
It is possible for this method to fail after creating some, but not
all, of the parent directories.
Not sure of which File API you are using. But find below the simplest code to create file along with folders using java.io package.
import java.io.File;
import java.io.IOException;
public class FileTest {
public static void main(String[] args) {
FileTest fileTest = new FileTest();
fileTest.createFile("C:"+File.separator+"folder"+File.separator+"file.txt");
}
public void createFile(String rootDir) {
String filePath = rootDir;
try {
if(rootDir.contains(File.separator)){
filePath = rootDir.substring(0, rootDir.lastIndexOf(File.separator));
}
File file = new File(filePath);
if(!file.exists()) {
System.out.println(file.mkdirs());
file = new File(rootDir);
System.out.println(file.createNewFile());
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Hi I am trying to load data into table using data files. I am using JDBC batch upload. After I load data from test.data into table, I want to validate it using expected-table.data. So in the following method first when test.data comes I want to do batch upload and then it should validate data using expected file but the following code does not work as expeted-data files comes in first iteration and test.data in second iteration. Please help I am new to file programming. Thanks in advance.
public static void loadFromFilesNValidateTable(Schema schema, final File folder)
{
for (final File fileEntry : folder.listFiles())
{
if (fileEntry.isDirectory())
{
loadFromFilesNValidateTable(schema,fileEntry);
}
else
{
if(fileEntry.getName().equals("test.data"))
{
BatchUpload.batchUpload(schema,fileEntry.getAbsolutePath());
}
if(fileEntry.getName().equals("expected-table.data"))
{
validateData(schema,fileEntry.getAbsolutePath());
}
}
}
}
Use a FileFilter
public static void loadFromFilesNValidateTable(TableDef schema, final File folder) {
// Process folders recursively
for(final File subFolder : folder.listFiles(new DirectoryFilter())){
loadFromFilesNValidateTable(schema, subFolder);
}
// Process data files
for (final File dataFileEntry : folder.listFiles(new FileNameFilter("test.data"))) {
BatchUpload.batchUpload(schema,dataFileEntry.getAbsolutePath());
}
// Process expected files
for (final File expectedFileEntry : folder.listFiles(new FileNameFilter("expected-table.data"))) {
validateData(schema,expectedFileEntry.getAbsolutePath());
}
}
public class FileNameFilter implements FileFilter {
private String name;
public FileNameFilter(String name){
this.name = name;
}
public boolean accept(File pathname){
return pathname.getName().equals(name)
}
}
public class DirectoryFilter implements FileFilter {
public boolean accept(File pathname){
return pathname.isDirectory();
}
}
Note: Apache commons-io provides a lot of FileFilters ready to use http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/filefilter/package-summary.html
I have 2 things to suggest you:
1. Change equals method with matches method. Matches method is the best method to compare
Strings.
2. Try to separate the moment in which you do batchUpload from that in which you do
validateData. Maybe you jump some files. For example the algorithm finds first the
"expected-table.data" file and then the "test.data" file. In this case it doesn't validate
the file. I hope my answer is usefull and I hope I have understood your problem : )
You should change the algorithm to something like this:
for (each directory in current directory) {
loadFromFilesNValidateTable(schema, directory);
}
if (current directory contains file "test.data") {
batchUpload();
if (current directory contains file "expected-table.data") {
validateData();
}
}
I already have a code that works, but I don't want it to actually delete the temp folder if possible. I am using the apache fileutils. Also does anyone know how to exclude folders from being deleted?
public class Cleartemp {
static String userprofile = System.getenv("USERPROFILE");
public static void main(String[] args) {
try {
File directory = new File(userprofile+"\\AppData\\Local\\Temp");
//
// Deletes a directory recursively. When deletion process is fail an
// IOException is thrown and that's why we catch the exception.
//
FileUtils.deleteDirectory(directory);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here's an actually recursive method:
public void deleteDirectory(File startFile, FileFilter ignoreFilter) {
if(startFile.isDirectory())
for(File f : startFile.listFiles()) {
deleteDirectory(f, ignoreFilter);
}
if(!ignoreFilter.accept(startFile)) {
startFile.delete();
}
}
Hand it a file filter set to return true for directories (see below) to make it not delete directories. You can also add exceptions for other files too
FileFilter folderFilter = new FileFilter() {
#Override
public boolean accept(File paramFile) {
return paramFile.isDirectory();
}
};
How about FileUtils.cleanDirectory ? It cleans a directory without deleting it.
You could also use Apache Commons DirectoryWalker if you need some filtering logic. One of the examples on the page includes FileCleaner implementation.
Simple,
Use isDirectory() to exclude it from being deleted.
Refer here: http://docs.oracle.com/javase/1.4.2/docs/api/java/io/File.html#isDirectory()
First ever post, don't consider myself an expert but am stuck with 1.4...
Here's a recursive delete method that works well, deletes all files and subfolders within a parent folder then the parent folder itself, assumes the File being passed is a directory as it is in my case.
private void deleteTemp(File tempDir) {
File[] a = (tempDir.listFiles());
for (int i = 0; i < a.length; i++) {
File b = a[i];
if (b.isDirectory())
deleteTemp(b);
b.delete();
}
tempDir.delete();
}
I want web service to make response as a zip file.
Generally there is nothing hard to do. But there is one thing I want to know:
Can I zip file without saving it to the hard disk, even if it's very large (100Mb - 500Mb)?
Now I'm using this nice hack. And i want to extend it with ziping functionality without creating new files on the file system.
public class TempFileInputStream extends FileInputStream {
private File file;
public TempFileInputStream(File file) throws FileNotFoundException {
super(file); // TO WANT: to pass here already zipped stream
this.file = file;
}
#Override
public void close() throws IOException {
super.close();
if (!file.delete()) {
// baad
} else {
// good
}
}
}
If I can, then what is the better/optimal way to do it ?
Thanks for any help !
take a look at this:
http://download.oracle.com/javase/1.4.2/docs/api/java/util/zip/ZipOutputStream.html
hope that helps...