Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/jsf/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从文本文件中的特定行获取表的值?_Java_Jdbc - Fatal编程技术网

Java 如何从文本文件中的特定行获取表的值?

Java 如何从文本文件中的特定行获取表的值?,java,jdbc,Java,Jdbc,我正在制作一个程序,从文本文件中读取数据,并将它们存储在mysql的表中。 在我的程序中,用户将给出文件所在的目录,然后程序将只找到.txt文件并继续。之后将创建一个表,它将有2个字段,在这些字段中我将插入文本文件中的值 我的问题是我不知道怎么做!我会向你解释我的意思!在我的程序中,我将创建带有字段(ID、名称)的表。这些字段的值必须取自文本文件。所有文件如下所示: 如您所见,ID位于文件的第三行,名称位于第五行。有谁能帮我导入表中ID和Name的值吗?如何每次只从文件中获取这些值 执行第一步的

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

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

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

执行第一步的代码是:

公共静态void main(字符串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();
}

}

你应该尽量不要重新发明轮子

使用
FileNameExtensionFilter
来过滤
.txt
文件,此类来自swing,但可以在普通java中使用

检查每一行是否与正则表达式模式匹配,这样您就可以在验证该行的同时消化该行

创建一个保存此信息的
Person
对象,并返回
Person
集合,这样您就可以将文件读取行为从数据库访问层封装起来

将所有这些放在一个名为
FileReader
类中,您可以得到如下内容:

public class FileReader {

    private final Pattern linePattern = Pattern.compile("^(\\w++)\\s++(\\w++)\\s*+$");
    private final Pattern lineBreakPattern = Pattern.compile("\r?\n");
    private final FileFilter txtFilter = new FileNameExtensionFilter("*.txt", "txt");
    private final File txtFolder;

    public FileReader(File txtFolder) {
        this.txtFolder = txtFolder;
    }

    public List<Person> readFiles() {
        final List<Person> people = new LinkedList<>();
        for (final File txtFile : txtFolder.listFiles()) {
            if (txtFilter.accept(txtFile)) {
                people.add(readFile(txtFile));
            }
        }
        return people;
    }

    private Person readFile(File txtFile) {
        try (final Scanner scanner = new Scanner(txtFile)) {
            scanner.useDelimiter(lineBreakPattern);
            final Person person = new Person();
            while (scanner.hasNext()) {
                final String line = scanner.next();
                final Matcher matcher = linePattern.matcher(line);
                if (matcher.matches()) {
                    switch (matcher.group(1).toUpperCase()) {
                        case "ID":
                            person.setId(Integer.parseInt(matcher.group(2)));
                            break;
                        case "NAME":
                            person.setName(matcher.group(2));
                            break;
                        default:
                            throw new IOException("Illegal line '" + matcher.group() + "'.");
                    }
                }
            }
            return person;
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    }

    public static final class Person {

        private int id;
        private String name;

        public int getId() {
            return id;
        }

        public void setId(int id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }
}
  • ^
    是“开始锚”,即线从这里开始
  • (\\w++)
    表示捕获任意数量的单词字符
  • \\s++
    表示跳过任意数量的空白字符
  • (\\w++)
    同上
  • \\s*+
    表示跳过零个或多个空白字符
  • $
    是“端锚”,即线的末端
因此,如果模式匹配,我们有一条有效的线。此外,在验证我们抓取的“组”字符时,这些是我们的关键和价值

接下来,我们在第一个组中使用
开关
,这是使用带有
String
s的Java7开关。我们根据键的值填充
person
,在需要的地方解析
int

最后,我们返回被填充的人

这个
应该可以帮助您顺利实现目标-将
Person
对象插入数据库的sql操作非常简单

您可能希望在文件读取过程中添加更多验证,例如检查是否同时找到
名称
ID
。我将此留作练习。

BufferedReader br=new BufferedReader(new FileReader(new File)(“path/to/File”));
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();
字符串currentLine=br.readLine(); Map nameByID=new HashMap(); while(currentLine!=null){ String[]tokens=currentLine.split(“\t”); intid=Integer.parseInt(标记[2]); 字符串名称=令牌[4]; nameByID.put(id,name); currentLine=br.readLine(); } br.close();
nameByID
将具有您需要的名称和ID


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

文本文件中的字段是否有一个简单的字符分隔?例如逗号或制表符?我在下面发布的代码应该从.txt文件中提取名称和ID字段。这段代码在很多地方都是错误的。首先,您需要将
id
解析为
int
。其次,您需要关闭
BufferedReader
,如果您使用的是Java 7,请使用参考资料进行尝试。@Boristeider很好的调用,修复了这些问题。没有在这台机器上设置java开发环境,很容易错过Stuff。Map nameByID=new HashMap()中也有错误;它不接受这种情况。我必须做什么?尝试Map nameByID=newhashmap();我上面写的代码只适用于Java7+,现在编辑它以反映这一变化
^(\\w++)\\s++(\\w++)\\s*+$
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();