如何从文本文件中的特定行获取表的值? [英] how get values for table from specific row in text files?

查看:81
本文介绍了如何从文本文件中的特定行获取表的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我制作了一个程序,可以从文本文件中读取数据并将它们存储在mysql的表中. 在我的程序中,用户将提供文件所在目录,然后程序将仅找到.txt文件并继续.之后将创建一个表,该表将具有2个字段,在这些字段中,我将从文本文件中插入值.

我的问题是我不知道怎么做!我会向你解释我的意思!在我的程序中,我将创建带有字段(ID,名称)的表.这些字段的值必须取自文本文件.所有文件如下:

如您所见,ID位于文件的第三行,名称位于第五行.谁能帮我导入表中ID和Name的值?如何每次从文件中仅获取这些值?

第一步的代码是:

公共静态void main(String 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(Connection con,字符串表名){

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;

}

解决方案

BufferedReader br = new BufferedReader(new FileReader(new File("path/to/file")));

String currentLine = br.readLine();

Map<Integer, String> nameByID = new HashMap<Integer, String>(); 
while (currentLine != null) {

  String[] tokens = currentLine.split("\t");
  int id = Integer.parseInt(tokens[2]);
  String name = tokens[4];
  nameByID.put(id, name);
  currentLine = br.readLine();

}

br.close();

nameByID将具有您需要的名称和ID.

请注意,对于创建新的BufferedReader的调用,对readLine()的调用以及关闭BufferedReader的调用,需要一些异常处理.我之所以没有插入它,是因为我不记得它了,但是如果您使用的是Netbeans或Eclipse,则您的IDE会提示您插入它

i making a program where I would read data from text files and store them in tables in mysql. In my program the user would give the directory of where the files are, then the program would find only the .txt files and would continue. Afterwards a table would be created and it would have 2 fields and in these fields I would insert the values from the text file.

My issue is that i don't know how! I would explain you what I mean! In my program I would create table with fields (ID, Name). The values of these fields must be taken from the text file. All the files are as the below:

As you can see the ID is in the third row of the file and the Name is in the fifth. Could anyone help me how can I import the values for ID and Name in the table?How can i get only these values each time from the files?

The code for doing the first steps is:

public static void main(String args[]) throws Exception {

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();
}

}

private static String getCreateTable1(Connection 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;

}

解决方案

BufferedReader br = new BufferedReader(new FileReader(new File("path/to/file")));

String currentLine = br.readLine();

Map<Integer, String> nameByID = new HashMap<Integer, String>(); 
while (currentLine != null) {

  String[] tokens = currentLine.split("\t");
  int id = Integer.parseInt(tokens[2]);
  String name = tokens[4];
  nameByID.put(id, name);
  currentLine = br.readLine();

}

br.close();

nameByID will have the names and IDs you need.

Note that some exception handling is required for calls to create a new BufferedReader, for calls to readLine(), and to close the BufferedReader. I didn't insert this because I couldn't remember it off the top of my head but your IDE should prompt you to insert if you're using something like Netbeans or Eclipse

这篇关于如何从文本文件中的特定行获取表的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆