JAVA和Sqlite数据库的MAP问题

发布于 2024-11-02 17:55:29 字数 5347 浏览 1 评论 0原文

我还有一个问题要问你: 下面的代码执行以下操作

  1. 对于文件夹中的每个文件

  2. 打开文件并读取其内容

  3. Take并将每一行划分为标记

  4. 将每个标记(单词)保存在 hasMap 中

  5. 准备数据库查询 (选择表单单词 ...)

  6. 对于在标记和数据库中包含的单词之间找到的每个匹配项,如果为 true,则写入 1.0,否则写入 0.0;< /p>

此时出现问题

try{
    while (rs_mail.next()) {
        if(result_m.contains(rs_mail.getString("voc_w").toString()))  //HERE I GET THE ERROR! java.lang.NullPointerException
            out_final.print("1.0;"); 
        else
            out_final.print("0.0;"); 
    }//Close While
}       //Close TRY
finally{
    rs_mail.close();
    //result_m.clear();
    mail.clear(); //Clear MAP
}

完整代码下方

String path ="C:/Users/.../file";
File currentDIR = new File("C:/Users/.../file");
File files_mail[]=currentDIR.listFiles();
String tmp_mail="";

// prepares the file tmpTraning.txt to receive value 1.0, 0.0 obtained by comparison with database
PrintWriter out_final=null;
File ff=new File("C:/Users/.../tmpTraning.txt");

//Seach for File in DIR
for( File fX : files_mail ){
    String name_Filex = fX.getName();
    FileReader fr = null;
    BufferedReader fINx = null;
    String sx;
    //Create MAP 
    Map<String, Set<String>> mail = new HashMap<String, Set<String>>();
    //Open File
    try{
        Set<String> sq = new HashSet<String>();

        fr = new FileReader(path+"/"+name_Filex);
        fINx = new BufferedReader(fr);
        sx = fINx.readLine();

        //scroll the file
        while(sx != null) {
            StringTokenizer stq = new StringTokenizer(sx);
            while(stq.hasMoreTokens()) { //Extract form line the single word
                tmp_mail = stq.nextToken();

                sq.add(tmp_mail.toString().toLowerCase()); //add the word to sq -> HashMap
                mail.put(nome_Filex, sq);

            }// Close st.hasMoreTokens()

            sx = fINx.readLine();
        } //Close  while for scroll File
        fr.close(); //Close fileReader
        sq.clear(); //Clear HasSet

    } //Close il TRAY
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    Set<String> result_m = mail.get(name_Filex);
    ResultSet rs_mail = stmt.executeQuery("SELECT DISTINCT voc.words as voc_w FROM voc_words as voc");

    //Prepare for writing on the file " tmpTraning.txt " 
    OutputStreamWriter fout_f = new OutputStreamWriter(new FileOutputStream(ff,true));
    out_final = new PrintWriter(fout_f);

    try{
        while (rs_mail.next()) {
            //If the word extract from the database is in MAP (name_Filex) then print 1.0; on the file tmpTraning.txt
            if(result_m.contains(rs_mail.getString("voc_w").toString()))  //HERE I GET THE ERROR! java.lang.NullPointerException
                out_final.print("1.0;"); 
            else
                //else print 0.0;
                out_final.print("0.0;"); 
        }
    }       //Close TRY
    finally{
        rs_mail.close();
        //result_m.clear();
        mail.clear(); //Clear MAP
    }

    out_final.println(""); //Send CR char ASCII to set the coursor for the next file on the new line
    out_final.close();
    out_final.flush();
} // End SCAN DIR

感谢您的建议!

代码更改- 打印result_m的内容

String path ="...";
File currentDIR = new File("...");
File files_mail[]=currentDIR.listFiles();
String tmp_mail="";

// prepares the file tmpTraning.txt to receive value 1.0, 0.0 obtained by comparison with database
PrintWriter out_final=null;
File ff=new File("...");

//Seach for File in DIR
for( File fX : currentDIR.listFiles() ){
    String name_Filex = fX.getName();

    String sx;
    //Create MAP 
    Map<String, Set<String>> mail = new HashMap<String, Set<String>>();
    //Open File
    try{
        Set<String> sq = new HashSet<String>();
        BufferedReader fINx = new BufferedReader(new FileReader(fX));
        sx = fINx.readLine();
        //scroll the file
        while(sx != null) {
            StringTokenizer stq = new StringTokenizer(sx);
            while(stq.hasMoreTokens()) { //Extract form line the single word
                tmp_mail = stq.nextToken();

                sq.add(tmp_mail.toString().toLowerCase()); //add the word to sq -> HashMap
                mail.put(name_Filex, sq);

            }// Close st.hasMoreTokens()

            sx = fINx.readLine();
        } //Close  while for scroll File
        fr.close(); //Close fileReader
        sq.clear(); //Clear HasSet

    } //Close il TRAY
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    /*
     * print the contents of  result_m
     */

    System.out.println("----- START FILE -----");
    Set<String> result_m = mail.get(name_Filex);
    Object[] toArray_m = mail.get(name_Filex).toArray();
    for (int ncc=0; ncc<result_m.size();ncc++){
        System.out.println(toArray_m[ncc]);
    }
    System.out.println("----- END  FILE  -----");


} // End SCAN DIR

如果程序读取的文件包含空行(无字符,无字符串),则保存空值

I have another question for you:
The code below does the following

  1. For each file in a folder

  2. Open the file and read its contents

  3. Take and divide each line into tokens

  4. Save each token (word) in a hasMap

  5. Prepare a database query (Select form words ...)

  6. For each match found between the tokens and the words contained in the database Write 1.0, if true, otherwise 0.0;

The problem arises at this point:

try{
    while (rs_mail.next()) {
        if(result_m.contains(rs_mail.getString("voc_w").toString()))  //HERE I GET THE ERROR! java.lang.NullPointerException
            out_final.print("1.0;"); 
        else
            out_final.print("0.0;"); 
    }//Close While
}       //Close TRY
finally{
    rs_mail.close();
    //result_m.clear();
    mail.clear(); //Clear MAP
}

Below the complete code:

String path ="C:/Users/.../file";
File currentDIR = new File("C:/Users/.../file");
File files_mail[]=currentDIR.listFiles();
String tmp_mail="";

// prepares the file tmpTraning.txt to receive value 1.0, 0.0 obtained by comparison with database
PrintWriter out_final=null;
File ff=new File("C:/Users/.../tmpTraning.txt");

//Seach for File in DIR
for( File fX : files_mail ){
    String name_Filex = fX.getName();
    FileReader fr = null;
    BufferedReader fINx = null;
    String sx;
    //Create MAP 
    Map<String, Set<String>> mail = new HashMap<String, Set<String>>();
    //Open File
    try{
        Set<String> sq = new HashSet<String>();

        fr = new FileReader(path+"/"+name_Filex);
        fINx = new BufferedReader(fr);
        sx = fINx.readLine();

        //scroll the file
        while(sx != null) {
            StringTokenizer stq = new StringTokenizer(sx);
            while(stq.hasMoreTokens()) { //Extract form line the single word
                tmp_mail = stq.nextToken();

                sq.add(tmp_mail.toString().toLowerCase()); //add the word to sq -> HashMap
                mail.put(nome_Filex, sq);

            }// Close st.hasMoreTokens()

            sx = fINx.readLine();
        } //Close  while for scroll File
        fr.close(); //Close fileReader
        sq.clear(); //Clear HasSet

    } //Close il TRAY
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    Set<String> result_m = mail.get(name_Filex);
    ResultSet rs_mail = stmt.executeQuery("SELECT DISTINCT voc.words as voc_w FROM voc_words as voc");

    //Prepare for writing on the file " tmpTraning.txt " 
    OutputStreamWriter fout_f = new OutputStreamWriter(new FileOutputStream(ff,true));
    out_final = new PrintWriter(fout_f);

    try{
        while (rs_mail.next()) {
            //If the word extract from the database is in MAP (name_Filex) then print 1.0; on the file tmpTraning.txt
            if(result_m.contains(rs_mail.getString("voc_w").toString()))  //HERE I GET THE ERROR! java.lang.NullPointerException
                out_final.print("1.0;"); 
            else
                //else print 0.0;
                out_final.print("0.0;"); 
        }
    }       //Close TRY
    finally{
        rs_mail.close();
        //result_m.clear();
        mail.clear(); //Clear MAP
    }

    out_final.println(""); //Send CR char ASCII to set the coursor for the next file on the new line
    out_final.close();
    out_final.flush();
} // End SCAN DIR

Thanks for any advice!

Code changes - print the contents of result_m:

String path ="...";
File currentDIR = new File("...");
File files_mail[]=currentDIR.listFiles();
String tmp_mail="";

// prepares the file tmpTraning.txt to receive value 1.0, 0.0 obtained by comparison with database
PrintWriter out_final=null;
File ff=new File("...");

//Seach for File in DIR
for( File fX : currentDIR.listFiles() ){
    String name_Filex = fX.getName();

    String sx;
    //Create MAP 
    Map<String, Set<String>> mail = new HashMap<String, Set<String>>();
    //Open File
    try{
        Set<String> sq = new HashSet<String>();
        BufferedReader fINx = new BufferedReader(new FileReader(fX));
        sx = fINx.readLine();
        //scroll the file
        while(sx != null) {
            StringTokenizer stq = new StringTokenizer(sx);
            while(stq.hasMoreTokens()) { //Extract form line the single word
                tmp_mail = stq.nextToken();

                sq.add(tmp_mail.toString().toLowerCase()); //add the word to sq -> HashMap
                mail.put(name_Filex, sq);

            }// Close st.hasMoreTokens()

            sx = fINx.readLine();
        } //Close  while for scroll File
        fr.close(); //Close fileReader
        sq.clear(); //Clear HasSet

    } //Close il TRAY
    catch (FileNotFoundException ex) {
        ex.printStackTrace();
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    /*
     * print the contents of  result_m
     */

    System.out.println("----- START FILE -----");
    Set<String> result_m = mail.get(name_Filex);
    Object[] toArray_m = mail.get(name_Filex).toArray();
    for (int ncc=0; ncc<result_m.size();ncc++){
        System.out.println(toArray_m[ncc]);
    }
    System.out.println("----- END  FILE  -----");


} // End SCAN DIR

if the file read by the program contains blank lines (no char, no string), it saves a null value

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

最好是你 2024-11-09 17:55:29

您在字符串上调用 toString() 是否有充分的理由?如果 getString("voc_w")null,那么它将导致您的异常。

正如 manji 在评论中指出的那样,要么是我提到的调用,要么是 result_m Setnull

Is there a good reason that you are calling toString() on a string? If getString("voc_w") is null, then it will cause your exception.

As manji pointed out in the comment, it's either the call I mentioned, or the result_m Set that are null.

赠我空喜 2024-11-09 17:55:29

不幸的是,您的代码存在很多问题。这是我立即想到的一个

您正在使用字符串操作来创建要传递给 FileReader 构造函数的文件名,尽管据我所知,正在打开的文件是从目录列表返回的文件。那只是自找麻烦。相反,代码最好像这样编写......

// Lots of things are omitted; this is just a sketch...
String path = "...";
File currentDIR = new File(path);
for (File fX : currentDIR.listFiles()) {
    try {
        BufferedReader fINx = new BufferedReader(new FileReader(fX));
        // ...
    } catch (IOException e) {
        e.printErrorStack();
    }
}

但是,您遇到的问题比这更多。例如,使用 sq.clear() 会产生不好的代码味道。您刚刚在 Map 中存放了对该 Set 的引用;你为什么又删除它的内容?变量超出范围;您可以简单地忽略该代码。 clear() 的下游后果是稍后的 result_m 将是一个空集,因此其 contains 测试将始终返回 false 。我无法立即判断这是否是您的流氓 null 的原因,但是根据您声称想要做的事情,它一定是错误的

尝试将该代码重构为几个更小的部分,更容易验证其正确性。我建议首先:从文件中获取单词集(作为参数提供)的私有方法,将单词集与数据库进行比较的私有方法,以及将这两个方法与一些循环结合起来以实现的方法你的总体目标。

There are a great many issues with your code, unfortunately. Here's one that springs to my eye immediately.

You are using string manipulation to create the filename that you are passing in to the FileReader constructor, despite the fact that as far as I can see the file being opened is one returned from a listing of the directory. That's just asking for trouble. Instead, the code would be better off written more like this...

// Lots of things are omitted; this is just a sketch...
String path = "...";
File currentDIR = new File(path);
for (File fX : currentDIR.listFiles()) {
    try {
        BufferedReader fINx = new BufferedReader(new FileReader(fX));
        // ...
    } catch (IOException e) {
        e.printErrorStack();
    }
}

However, you have more problems than that. For example, the use of sq.clear() has bad code smell. You've just stowed a reference to that Set in the Map; why are you deleting its contents again? The variable is falling out of scope; you can simply leave that code out. The down-stream consequences of that clear() are that result_m later on will be an empty set, so its contains test will always return false. I can't tell offhand whether that's the cause of your rogue null, but it's got to be wrong on the basis of what you're claiming to want to do.

Try refactoring that code into several smaller pieces that are easier to verify correct. I suggest as a first cut: a private method to get the Set of words from a File (supplied as argument), a private method to compare a Set of words against the database, and a method that combines those two with some looping to achieve your overall goal.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文