4

I have a source folder with Java source files. These Java files have different packages. Using javac command I can generate the package structure, but the packages will contain the class files not the source files.

Is there any API which generates package structure from Java files and puts Java files into the specific package

JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
Saket
  • 431
  • 2
  • 6
  • 15
  • 2
    So your .java files are not in the correct structure to begin with? It might be a stupid question, but: why? – Joachim Sauer Jan 09 '12 at 11:30
  • if you specify the output folder same as your source files root folder, javac will put the class files alongside the source files. – Manish Jan 09 '12 at 11:31
  • @ManishSharma that's not what the OP is asking. – adarshr Jan 09 '12 at 11:33
  • I second @JoachimSauer's reasoning. Why aren't they in the correct structure to start with? – adarshr Jan 09 '12 at 11:34
  • the above structure will serve as an input for a UML diagram generator project which i am working on currently. so its the input which has this structure. – Saket Jan 09 '12 at 11:36
  • @user1118872 How many unique packages are there? Is it just a few or are they in hundreds? – adarshr Jan 09 '12 at 11:41
  • I think that the answer is probably "No". It is better if you create or keep the files in the correct directories to start with. – Stephen C Jan 09 '12 at 11:53
  • @StephenC thats precisely what i want to do. but i cant manually create package structure for every input – Saket Jan 09 '12 at 11:56
  • @user1118872 Presuming that you're on Windows, I wrote a batch script to do that. – adarshr Jan 09 '12 at 12:36
  • thanks @adarshr i am on ubuntu :). how to execute this script there – Saket Jan 09 '12 at 12:46
  • @user1118872 Please see my updated answer. Similar instructions apply. – adarshr Jan 09 '12 at 13:18

2 Answers2

2

Presuming that you're on Windows, I wrote a batch script to do that.

Copy the content below into source.bat, place source.bat in the same directory where you find all your .java files and just run it.

@echo off
@setlocal enabledelayedexpansion

for /f "usebackq delims=" %%f in (`dir /s /b *.java`) do (
    set file=%%~nxf

    for /f "usebackq delims=" %%p in (`findstr package %%~nxf`) do (
        set package=%%p

        set package=!package:*.java:=!
        set package=!package:package =!
        set package=!package:;=!
        set package=!package:.=\!

        echo Expanding !package!...

        mkdir !package!
        xcopy /f %%~nxf !package!
    )
)

@endlocal

If however you're on Unix/Linux, here is a bash script. I'm sure this can be done in a much better and concise way but it definitely works.

#! /bin/bash

for file in *.java
do
    package=`grep -h 'package' $file`
    package=`echo $package | sed 's/package//g'`
    package=`echo $package | sed 's/;//g'`
    package=`echo $package | sed 's/\./\//g'`

    echo Expanding $package...
    mkdir -p $package

    cp $file $package
done
adarshr
  • 61,315
  • 23
  • 138
  • 167
1

Here's what I came up for this problem.It opens the java file, reads the package name, generates the structure and copies the file to that structure. Suggestions for improvement are welcome. :)

public final class FileListing {

private Map packageMap;


public void createPackageStructure(String sourceDir) throws FileNotFoundException 
{
    FileListing fileListing = new FileListing();
File startingDirectory= new File(sourceDir);

    fileListing.packageMap = new HashMap();
    List<File> files = fileListing.getFileListing(startingDirectory,   fileListing.getPackageMap());

    fileListing.moveFiles(fileListing.packageMap);

}


public List<File> getFileListing(File aStartingDir, Map packageMap) throws   FileNotFoundException 
{
    validateDirectory(aStartingDir);
    List<File> result = getFileListingNoSort(aStartingDir,packageMap);
    Collections.sort(result);
    return result;
}


private List<File> getFileListingNoSort(File aStartingDir, Map packageMap) throws FileNotFoundException 
{  
    List<File> result = new ArrayList<File>();
    File[] filesAndDirs = aStartingDir.listFiles();
    List<File> filesDirs = Arrays.asList(filesAndDirs);

    for(File file : filesDirs) 
    {
       result.add(file); 
       if(file.isFile())
       {
           packageMap.put(file, readPackageName(file.getAbsolutePath()).replace(".", "/").replace(";", "/"));
       }
       else 
       {
           //must be a directory
           //recursive call!
           List<File> deeperList = getFileListingNoSort(file,packageMap);
           result.addAll(deeperList);
       }
    }
return result;
}

public String readPackageName(String filePath)
{
  String packageName=null;
  String line;
  String temp[] = new String[2];
  BufferedReader br=null;
  try{
      File javaFile =  new File(filePath);
      br = new BufferedReader(new FileReader(javaFile));
      while((line=br.readLine())!=null)
      {
          if(line.indexOf("package")!=-1)
          {
              temp = line.split(" ");
              break;
          }
      }
      br.close();

  }catch(FileNotFoundException fnfe)
  {
      fnfe.printStackTrace();
  }catch(IOException ioe)
  {
      ioe.printStackTrace();
  }
  return temp[1];
}

public void moveFiles(Map packageMap)
{
 Set keySet = packageMap.keySet();
 Iterator it = keySet.iterator();
     File sourceFile, destFile, destDirs;
 InputStream in = null;
 OutputStream out = null;
 byte[] buf = new byte[1024];
 int len;

     try{
     while(it.hasNext())
         {
        sourceFile = (File)it.next();
        destDirs = new File("src/"+(String)packageMap.get(sourceFile));
        destFile = new File("src/"+   (String)packageMap.get(sourceFile)+"/"+sourceFile.getName());
        destDirs.mkdirs();
        in = new FileInputStream(sourceFile);
        out = new FileOutputStream(destFile);

        while((len = in.read(buf)) > 0){
            out.write(buf, 0, len);
        }
         }
   }catch(FileNotFoundException fnfe)
   {
       fnfe.printStackTrace();
   }catch(IOException ioe)
   {
       ioe.printStackTrace();
   }
}

static private void validateDirectory (File aDirectory) throws FileNotFoundException 
{
  if (aDirectory == null) {
    throw new IllegalArgumentException("Directory should not be null.");
  }
  if (!aDirectory.exists()) {
    throw new FileNotFoundException("Directory does not exist: " + aDirectory);
  }
  if (!aDirectory.isDirectory()) {
    throw new IllegalArgumentException("Is not a directory: " + aDirectory);
  }
  if (!aDirectory.canRead()) {
    throw new IllegalArgumentException("Directory cannot be read: " + aDirectory);
  }
}

public Map getPackageMap()
{
  return this.packageMap;
}
} 
Saket
  • 431
  • 2
  • 6
  • 15