[英]Create a Folder Structure from User input
我在下面創建了一個快速示例。 我想基於用戶的文本輸入創建文件夾結構。 例如:
文本字段1是: 2001
文本字段2是: test
則文件夾結構為c:\\2001\\test
它是一個更大的應用程序的一部分,但這就是讓我感到困惑的地方。 任何幫助表示贊賞。
import java.io.File;
import javax.swing.*;
public class CreateDirectory extends JFrame {
public static void main(String args[]) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
new CreateDirectory().setVisible(true);
}
});
}
public CreateDirectory() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Create New Job App");
panel pan = new panel();
add(pan.panel);
pack();
setVisible(true);
}
}
class panel {
private JButton btn1 = new JButton("Create");
private JTextField txt1 = new JTextField(10);
private JTextField txt2 = new JTextField(10);
JPanel panel;
public panel() {
panel = new JPanel();
panel.add(btn1);
panel.add(txt1);
panel.add(txt2);
btn1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
btn1ActionPerformed(evt);
}
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {
File files = new File("C:\\Directory2\\Sub2\\Sub-Sub2");
if (!files.exists()) {
if (files.mkdirs()) {
} else {
}
}
}
});
}
}
您所需要做的就是提到要像這樣創建的目錄
private void btn1ActionPerformed(java.awt.event.ActionEvent evt) {
File files = new File("c:\\"+txt1.getText()+"\\"+txt2.getText());
if (!files.exists()) {
if (files.mkdirs()) {
} else {
}
}
}
希望對您有所幫助!
我希望您有button,所以在它的動作偵聽器方法上,從兩個文本框中獲取值,驗證它們,然后調用類似這樣的方法
private void createDirectories(String textInputOne , String textInputTwo){
String root="";//Your base directory or Drive in your case c:/
String totalPath=root+File.separator+textInputOne+File.separator+textInputTwo;
File folder=new File(totalPath);
if(!folder.exists()){
folder.mkdirs();
}else{
System.out.println("already exists");
}
}
我希望這能奏效,並且如果您在基本文件夾/驅動器中沒有權限,則mkdirs()
將返回false。
也檢查一下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.