compile Java Files from Windows command line - Android App

Android examples for App:APK File

Description

compile Java Files from Windows command line

Demo Code


//package com.book2s;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import java.util.List;

public class Main {
    private static final String ANDROID_JAR_PATH = "D:\\android_sdk_for_studio\\platforms\\android-22\\android.jar";
    private static final String batchDir = System.getProperty("user.dir")
            + "\\batch\\";

    private static void compileJavaFiles(String projectDir) {
        StringBuffer command = new StringBuffer();
        command.append("javac -target 1.5 -bootclasspath ")
                .append(ANDROID_JAR_PATH).append(" -d ").append(projectDir)
                .append("\\bin ");
        List<String> javaFilePaths = new ArrayList<String>();
        findJavaFiles(projectDir + "\\src", javaFilePaths);
        findJavaFiles(projectDir + "\\gen", javaFilePaths);
        for (String javaPath : javaFilePaths) {
            command.append(javaPath).append(" ");
        }/* w w  w .ja  v  a2s  . c om*/
        command.append("-classpath ").append(projectDir)
                .append("\\libs\\.*jar");
        buildExeBatchFiles(command.toString(), "2.bat");
    }

    private static void findJavaFiles(String projectDir,
            List<String> javaFilePaths) {
        File file = new File(projectDir);
        File[] files = file.listFiles();
        if (files == null || files.length == 0) {
            return;
        }
        for (File f : files) {
            if (f.isDirectory()) {
                findJavaFiles(f.getAbsolutePath(), javaFilePaths);
            } else {
                if (f.getAbsolutePath().endsWith(".java")) {
                    javaFilePaths.add(f.getAbsolutePath());
                }
            }
        }
    }

    private static void buildExeBatchFiles(String command, String fileName) {
        System.out.println(command);
        if (!new File(batchDir).exists()) {
            new File(batchDir).mkdirs();
        }
        String filePath = batchDir + fileName;
        try {
            writeFile(filePath, command);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void writeFile(String filePath, String content)
            throws IOException {
        FileWriter fw = new FileWriter(filePath);
        PrintWriter out = new PrintWriter(fw);
        out.write(content);
        out.println();
        fw.close();
        out.close();
    }
}

Related Tutorials