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() { @Override public void actionPerformed(ActionEvent e) { JFileChooser dlg = new JFileChooser(path.getText()); FileFilter filter = new FileFilter() { @Override public String getDescription() { return null; } @Override public 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() { @Override public void actionPerformed(ActionEvent arg0) { try { // key function new 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() { @Override public 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(); } } @Override public void windowActivated(WindowEvent e) { } @Override public void windowClosed(WindowEvent e) { } @Override public void windowDeactivated(WindowEvent e) { } @Override public void windowDeiconified(WindowEvent e) { } @Override public void windowIconified(WindowEvent e) { } @Override public 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> { @Override public 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 function String 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, ignore System.out.println("file is hidden: " + file.getPath()); continue; } if (file.getName().startsWith(".")) { // do nothing, ignore System.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"?> <VisualStudioProject ProjectType="Visual C++" Version="7.10" Name="{{NAME}}" ProjectGUID="{{GUID}}" Keyword="Win32Proj"> <Platforms> <Platform Name="Win32"/> </Platforms> <Configurations> <Configuration Name="Debug|Win32" OutputDirectory="Debug" IntermediateDirectory="Debug" ConfigurationType="1" CharacterSet="2"> <Tool Name="VCCLCompilerTool" Optimization="0" PreprocessorDefinitions="WIN32;_DEBUG;_WINDOWS" MinimalRebuild="TRUE" BasicRuntimeChecks="3" RuntimeLibrary="5" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="TRUE" DebugInformationFormat="4"/> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/test.exe" LinkIncremental="2" GenerateDebugInformation="TRUE" ProgramDatabaseFile="$(OutDir)/test.pdb" SubSystem="2" TargetMachine="1"/> <Tool Name="VCMIDLTool"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCXMLDataGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <Tool Name="VCManagedWrapperGeneratorTool"/> <Tool Name="VCAuxiliaryManagedWrapperGeneratorTool"/> </Configuration> <Configuration Name="Release|Win32" OutputDirectory="Release" IntermediateDirectory="Release" ConfigurationType="1" CharacterSet="2"> <Tool Name="VCCLCompilerTool" PreprocessorDefinitions="WIN32;NDEBUG;_WINDOWS" RuntimeLibrary="4" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="TRUE" DebugInformationFormat="3"/> <Tool Name="VCCustomBuildTool"/> <Tool Name="VCLinkerTool" OutputFile="$(OutDir)/test.exe" LinkIncremental="1" GenerateDebugInformation="TRUE" SubSystem="2" OptimizeReferences="2" EnableCOMDATFolding="2" TargetMachine="1"/> <Tool Name="VCMIDLTool"/> <Tool Name="VCPostBuildEventTool"/> <Tool Name="VCPreBuildEventTool"/> <Tool Name="VCPreLinkEventTool"/> <Tool Name="VCResourceCompilerTool"/> <Tool Name="VCWebServiceProxyGeneratorTool"/> <Tool Name="VCXMLDataGeneratorTool"/> <Tool Name="VCWebDeploymentTool"/> <Tool Name="VCManagedWrapperGeneratorTool"/> <Tool Name="VCAuxiliaryManagedWrapperGeneratorTool"/> </Configuration> </Configurations> <References> </References> <Files> <!-- <Filter Name="Source Files" Filter="cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx" UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"> </Filter> <Filter Name="Header Files" Filter="h;hpp;hxx;hm;inl;inc;xsd" UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"> </Filter> <Filter Name="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>