[Java] 自動產生visual studio專案檔

來源:互聯網
上載者:User

visual studio在添加源碼的時候只能逐個檔案進行添加,有時候很麻煩。於是做了下面這個自動產生visual studio專案檔的工具。

這個工具有什麼用?等你哪天想用visual studio看linux kernel代碼的時候就知道了。

 

ProjectCreator.java 

package wsq;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.WindowEvent;import java.awt.event.WindowListener;import java.io.File;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Date;import java.util.Properties;import javax.swing.JButton;import javax.swing.JFileChooser;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JOptionPane;import javax.swing.JTextField;import javax.swing.filechooser.FileFilter;public class ProjectCreator {public static void main(String[] args) throws IOException {final JFrame frame = new JFrame("ProjectCreator");frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);frame.setSize(600, 400);frame.setLocation(200, 100);frame.getContentPane().setLayout(new java.awt.GridBagLayout());JLabel lb = new JLabel();lb.setText("Select project path:");final JTextField path = new JTextField(20);JButton btnBrows = new JButton("...");btnBrows.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent e) {JFileChooser dlg = new JFileChooser(path.getText());FileFilter filter = new FileFilter() {@Overridepublic String getDescription() {return null;}@Overridepublic boolean accept(File f) {return f.isDirectory();}};dlg.setFileFilter(filter);dlg.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);if (dlg.showOpenDialog(frame) == JFileChooser.APPROVE_OPTION) {try {path.setText(dlg.getSelectedFile().getCanonicalPath());} catch (IOException e1) {e1.printStackTrace();}}}});JButton btnRun = new JButton();btnRun.setLocation(60, 60);btnRun.setText("Run");btnRun.addActionListener(new ActionListener() {@Overridepublic void actionPerformed(ActionEvent arg0) {try {// key functionnew ProjectProc().process(path.getText());JOptionPane.showMessageDialog(frame, "finished");} catch (Exception e) {JOptionPane.showMessageDialog(frame, e.toString());}}});frame.getContentPane().add(lb);frame.getContentPane().add(path);frame.getContentPane().add(btnBrows);frame.getContentPane().add(btnRun);frame.setVisible(true);final Properties prop = new Properties();try {prop.load(new FileReader(ProjectProc.getConfigFileName()));} catch (IOException e) {e.printStackTrace();}path.setText(prop.getProperty("path"));frame.addWindowListener(new WindowListener() {@Overridepublic void windowClosing(WindowEvent arg0) {try {prop.setProperty("path", path.getText());String file = ProjectProc.getConfigFileName();prop.store(new FileWriter(file), (new Date()).toString());} catch (IOException e) {e.printStackTrace();}}@Overridepublic void windowActivated(WindowEvent e) {}@Overridepublic void windowClosed(WindowEvent e) {}@Overridepublic void windowDeactivated(WindowEvent e) {}@Overridepublic void windowDeiconified(WindowEvent e) {}@Overridepublic void windowIconified(WindowEvent e) {}@Overridepublic void windowOpened(WindowEvent e) {}});}}

 

ProjectProc.java

package wsq;import java.io.BufferedReader;import java.io.File;import java.io.FileWriter;import java.io.InputStream;import java.io.InputStreamReader;import java.util.Collections;import java.util.Comparator;import java.util.LinkedList;import java.util.UUID;public class ProjectProc {class FileComp implements Comparator<File> {@Overridepublic int compare(File o1, File o2) {return o1.getPath().compareTo(o2.getPath());}}static String[] g_ayExt = { "cpp", "h", "cxx", "c", "java", "hpp", "hxx","cs", "php" };static LinkedList<String> g_llExt = new LinkedList<String>();public static String getConfigFileName() {File f = new File("myconfig.conf");String path = f.getAbsolutePath();return path;}private boolean isSourceFile(String path) {if (g_llExt.size() == 0) {for (String e : g_ayExt) {g_llExt.add(e);}}int idx = path.lastIndexOf('.');if (idx <= 0) {return false;}String ext = path.substring(idx + 1);if (g_llExt.contains(ext)) {return true;} else {return false;}}public void process(String path) throws Exception {BufferedReader br = null;FileWriter fw = null;try {String full = "";InputStream templ = getClass().getResourceAsStream("template.vcproj.txt");br = new BufferedReader(new InputStreamReader(templ));while (br.ready()) {full += br.readLine() + "\r\n";}File f = new File(path);path = f.getAbsolutePath();if (!path.endsWith(File.separator)) {path = path + File.separator;}String projName = path.substring(path.lastIndexOf(File.separator, path.length() - 2) + 1,path.length() - 1);// key functionString result = SearchDir(path);result = result.replace(path, "");full = full.replace("{{NAME}}", projName);full = full.replace("{{GUID}}", "{" + UUID.randomUUID().toString()+ "}");full = full.replace("{{FILES}}", result);String resFile = path + projName + ".vcproj";fw = new FileWriter(resFile);fw.write(full.toCharArray());fw.flush();} catch (Exception e) {e.printStackTrace();throw e;} finally {if (br != null) {br.close();}if (fw != null) {fw.close();}}}/** * @param path *            絕對路徑 * @return string */private String SearchDir(String path) {if (!path.endsWith(File.separator)) {path = path + File.separator;}String name = path.substring(path.lastIndexOf(File.separator, path.length() - 2) + 1,path.length() - 1);String result = String.format("<Filter Name=\"%s\" Filter=\"\">", name);File dir = new File(path);File[] files = dir.listFiles();if (files == null) {result += "</Filter>";return result;}LinkedList<File> list = new LinkedList<File>();for (File file : files) {list.add(file);}FileComp c = new FileComp();Collections.sort(list, c);for (File file : list) {if (file.isHidden()) {// do nothing, ignoreSystem.out.println("file is hidden: " + file.getPath());continue;}if (file.getName().startsWith(".")) {// do nothing, ignoreSystem.out.println("file is start with '.': " + file.getPath());continue;}if (file.isDirectory()) {String sub = SearchDir(file.getPath());result += sub;} else {if (isSourceFile(file.getPath())) {String sub = String.format("<File RelativePath=\"%s\"></File>\r\n",file.getPath());result += sub;}}}result += "</Filter>";return result;}}

 

模板檔案:template.vcproj.txt

<?xml version="1.0" encoding="gb2312"?><VisualStudioProjectProjectType="Visual C++"Version="7.10"Name="{{NAME}}"ProjectGUID="{{GUID}}"Keyword="Win32Proj"><Platforms><PlatformName="Win32"/></Platforms><Configurations><ConfigurationName="Debug|Win32"OutputDirectory="Debug"IntermediateDirectory="Debug"ConfigurationType="1"CharacterSet="2"><ToolName="VCCLCompilerTool"Optimization="0"PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS"MinimalRebuild="TRUE"BasicRuntimeChecks="3"RuntimeLibrary="5"UsePrecompiledHeader="0"WarningLevel="3"Detect64BitPortabilityProblems="TRUE"DebugInformationFormat="4"/><ToolName="VCCustomBuildTool"/><ToolName="VCLinkerTool"OutputFile="$(OutDir)/test.exe"LinkIncremental="2"GenerateDebugInformation="TRUE"ProgramDatabaseFile="$(OutDir)/test.pdb"SubSystem="2"TargetMachine="1"/><ToolName="VCMIDLTool"/><ToolName="VCPostBuildEventTool"/><ToolName="VCPreBuildEventTool"/><ToolName="VCPreLinkEventTool"/><ToolName="VCResourceCompilerTool"/><ToolName="VCWebServiceProxyGeneratorTool"/><ToolName="VCXMLDataGeneratorTool"/><ToolName="VCWebDeploymentTool"/><ToolName="VCManagedWrapperGeneratorTool"/><ToolName="VCAuxiliaryManagedWrapperGeneratorTool"/></Configuration><ConfigurationName="Release|Win32"OutputDirectory="Release"IntermediateDirectory="Release"ConfigurationType="1"CharacterSet="2"><ToolName="VCCLCompilerTool"PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS"RuntimeLibrary="4"UsePrecompiledHeader="0"WarningLevel="3"Detect64BitPortabilityProblems="TRUE"DebugInformationFormat="3"/><ToolName="VCCustomBuildTool"/><ToolName="VCLinkerTool"OutputFile="$(OutDir)/test.exe"LinkIncremental="1"GenerateDebugInformation="TRUE"SubSystem="2"OptimizeReferences="2"EnableCOMDATFolding="2"TargetMachine="1"/><ToolName="VCMIDLTool"/><ToolName="VCPostBuildEventTool"/><ToolName="VCPreBuildEventTool"/><ToolName="VCPreLinkEventTool"/><ToolName="VCResourceCompilerTool"/><ToolName="VCWebServiceProxyGeneratorTool"/><ToolName="VCXMLDataGeneratorTool"/><ToolName="VCWebDeploymentTool"/><ToolName="VCManagedWrapperGeneratorTool"/><ToolName="VCAuxiliaryManagedWrapperGeneratorTool"/></Configuration></Configurations><References></References><Files><!--<FilterName="Source Files"Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx"UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"></Filter><FilterName="Header Files"Filter="h;hpp;hxx;hm;inl;inc;xsd"UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"></Filter><FilterName="Resource Files"Filter="rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx"UniqueIdentifier="{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}"></Filter>--><!--<Filter Name="core" Filter=""><File RelativePath=".\core\TimerHandler.h"></File></Filter>-->{{FILES}}</Files><Globals></Globals></VisualStudioProject>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.