我正在製作一個程序,我將從文本文件中讀取數據並將它們存儲在mysql表中。 在我的程序中,用戶會給出文件所在的目錄,然後程序將只能找到.txt文件並繼續。之後將創建一個表格,它將有2個字段,並在這些字段中插入文本文件中的值。如何從文本文件中的特定行獲取表的值?
我的問題是,我不知道如何!我會解釋你的意思!在我的程序中,我將創建帶有字段(ID,名稱)的表格。這些字段的值必須來自文本文件。所有的文件如下:
正如你所看到的ID是在文件的第三行,名稱是在第五。任何人都可以幫助我如何導入表中的ID和名稱值?我怎樣才能從文件中每次只獲得這些值?
做的第一個步驟的代碼是:
公共靜態無效主要(字符串ARGS [])拋出異常{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection(
"jdbc:mysql://localhost:3306/mydb", "", "");
String dirpath = "";
Scanner scanner1 = new Scanner(System.in);
while (true) {
System.out.println("Please give the directory:");
dirpath = scanner1.nextLine();
File fl = new File(dirpath);
if (fl.canRead())
break;
System.out.println("Error:Directory does not exists");
}
try {
String files;
File folder = new File(dirpath);
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isFile()) {
files = listOfFiles[i].getName();
if (files.endsWith(".txt") || files.endsWith(".TXT")) {
List<File> txtFiles = new ArrayList<File>();
txtFiles.add(listOfFiles[i]);
String[] parts = files.split("\\.");
String tablename = parts[0];
for (File txtFile : txtFiles) {
List sheetData = new ArrayList();
try {
FileReader in = new FileReader(txtFile);
BufferedReader br = new BufferedReader(in);
String line = br.readLine();
while (line != null) {
System.out.println(line);
line = br.readLine();
}
in.close();
} catch (Exception e) {
System.err.println("Error: " + e.getMessage());
}
getCreateTable1(con, tablename);
importData(con, txtFile, tablename);
}
}
}
}
} catch (Exception e) {
System.out.println();
}
}
私有靜態字符串getCreateTable1(連接CON, String tablename){
try {
Class.forName("com.mysql.jdbc.Driver");
Statement stmt = con.createStatement();
String createtable = "CREATE TABLE "
+ tablename
+ " (ID INT , name VARCHAR(255)";
System.out.println("Create a new table in the database");
stmt.executeUpdate(createtable);
} catch (Exception e) {
System.out.println(((SQLException) e).getSQLState());
System.out.println(e.getMessage());
e.printStackTrace();
}
return null;
}
是否有一個簡單的字符分隔字段文本文件?例如。逗號或製表符? –
是的,有標籤。 – dedmar
我在下面發佈的代碼應該從.txt文件中提取名稱和ID字段 –