是否有任何API可以从Java源文件生成软件包结构

4

我有一个包含Java源代码的源文件夹。这些Java文件有不同的包。使用javac命令,我可以生成包结构,但是这些包将包含类文件而不是源文件。

是否有任何API可以从Java文件生成包结构并将Java文件放入特定的包中?


2
你的 .java 文件一开始就不是正确的结构吗?这可能是一个愚蠢的问题,但是:为什么? - Joachim Sauer
如果您将输出文件夹指定为与源文件根文件夹相同的位置,javac会将类文件放置在源文件旁边。 - Manish
@ManishSharma,这不是OP所问的。 - adarshr
我认为答案可能是“不”。最好的方法是一开始就创建或保留正确目录中的文件。 - Stephen C
@StephenC 这正是我想做的。但我不能为每个输入手动创建包结构。 - Saket
显示剩余6条评论
2个回答

2
假设您使用的是Windows系统,我写了一个批处理脚本来完成这个任务。
将下面的内容复制到“source.bat”文件中,将“source.bat”文件放置在存放所有“.java”文件的同一目录下,然后运行它即可。
@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

如果你使用的是Unix/Linux系统,这里有一个bash脚本。我相信这可以以更好、更简洁的方式来实现,但它绝对有效。
#! /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

我建议使用package=$(grep -h -m 1 package "$file" | sed -e 's/.*package[[:space:]]\+\(.*\)[[:space:]]*;.*/\1/' -e 's/\./\//g')。这将一次性完成所有操作。 - Philipp Wendler
@PhilippWendler 谢谢。我喜欢一行代码! - adarshr

1

这是我为这个问题想到的解决方案。它打开Java文件,读取包名称,生成结构并将文件复制到该结构中。欢迎提出改进意见。 :)

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;
}
} 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接