java - JFileChooser和.txt文件解析问题

标签 java regex string file-io jfilechooser

我在解决 CCE 时遇到问题。这项任务要求 用户在运行时打开 .txt 文件,然后让编译器 对特定的正则表达式进行后台解析以确定它们是否 匹配或不匹配(例如 ACC 或 REJ),但问题是 用户必须使用 JFileChooser 打开文件。我读了很多书并且 在发布此内容之前进行研究,问题似乎是 JFileChooser,据我了解,它使用 java.io.File 本身,似乎 在这种情况下仅允许扫描程序解析 .txt 文件的输入。

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/class-use/File.html

所以,当我单独使用扫描仪读取文件中的所有文本行时 它“已编译”,但显示的所有控制台输出都是,例如“null null null null null”(例如,如果文件中有五行文本)。 为了方便起见,以下是将被考虑的 .txt 文件的示例 可接受(或 ACC,简写):编辑此示例应将每个规则打印在单独的行上

S:AB 答:0A 答:e 乙:1B B:e

我已经提供了我的源代码。请注意,charSequences 只是可行的 Scanner/BR 必须解析的正则表达式。另外,如果任何给定的行正在拒绝(REJ, 为简写),我们需要提醒用户然后立即终止。显然 我并不像我想象的那样理解这些类(class)......也许我需要 使用像 FileReader 这样的东西,我一开始就偏离了基础,但我只是 一般来说,对 java IO 的复杂性感到非常沮丧。真是令人沮丧 因为我投入了所有这些工作和努力,却很少有任何成果。

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException; 
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;

public class Simplified 
{


public Simplified() throws Exception
{   
    readLines();
}

public void readLines() throws Exception
{

    //MUST prompt user to use JFileChooser
    JFileChooser ranFi = new JFileChooser();
    //approve condition
    if(ranFi.showOpenDialog(null)==JFileChooser.APPROVE_OPTION)
    {
        //get selected file 
        Comparable<File> file = ranFi.getSelectedFile();
        //create a bufferedReader for the file 
        //BufferedReader br = new BufferedReader((Reader) file);
        BufferedReader br = null;

        //create local String object the refer to file's current line 
        String currentLine;

        /**************************
         * Length(LHS,RHS) = 1,1
         * --CharSequence compilations
         * ******************************
         */
        //ACC
        CharSequence fp100 = "[S][:][A-Ze0-1]";
        //ACC iff is NOT the very first line of text file 
        CharSequence fp101 = "[A-Z&&[^S]][:][A-Ze0-1]";


        /**************************
         * Length(LHS,RHS) = 1,2
         * --CharSequence compilations
         * ******************************
         */
        //ACC 
        CharSequence fp200 = "[S][:][A-Z0-1][A-Z0-1]";
        //ACC iff is NOT the very first line of text file 
        CharSequence fp201 = "[A-Z&&[^S]][:][A-Z0-1][A-Z0-1]";

        /**************************
         * Length(LHS,RHS) = 1,3 
         * --CharSequence compilations
         * ******************************
         */
        //ACC 
        CharSequence fp300 = "[S][:][A-Z0-1][A-Z0-1][A-Z0-1]";
        //ACC iff is NOT the very first line of text file 
        CharSequence fp301 = "[A-Z&&[^S]][:][A-Z0-1][A-Z0-1][A-Z0-1]";

        /**
         * Length(LHS,RHS) = 1,4 
         * --CharSequence compilations
         * ******************************
         */

        //REJ
        CharSequence fp400 = "[.][.][.][.][.][.]";


        //create a Scanner for the file 
        Scanner text = new Scanner((Readable) file);

        try
        {
            br = new BufferedReader((Reader) file);
            //while there are still lines to be read in the file 
            //where currentLine = present line of the bufferedReader
            while((currentLine = br.readLine()) != null)
            {

                //while the scanner still has lines to read in the file 
                while(text.hasNext())
                {


                //to remove trailing whitespace in the file, starting
                //@ the first line in the text file...
                String trimStartLine = currentLine.trim();

                //ALL feasible ACC permutations for starting line 
                if(trimStartLine.contains(fp100)||trimStartLine.contains(fp200)||trimStartLine.contains(fp300))
                {
                    System.out.println("first line valid...");


                }
                //ALL feasible REJ permutations for starting line
                else if(!trimStartLine.contains(fp100)||!trimStartLine.contains(fp200)||!trimStartLine.contains(fp300))
                {
                    System.out.println("invalid first line..." +
                            "...terminating");
                    System.exit(0);
                }

                //once again removing trailing whitespace in the file,
                //this time trimming the whitespace in the second line
                //of the file, provided that iff the first line of the
                //file was valid to begin with...
                String trim2ndLine = currentLine.trim();

                //permutations have now increased to 6 since "[S]" isn't
                //technically required for ANY line other than the first line 
                if(trim2ndLine.contains(fp100)||trim2ndLine.contains(fp101)||trim2ndLine.contains(fp200)||
                        trim2ndLine.contains(fp201)||trim2ndLine.contains(fp300)||trim2ndLine.contains(fp301))
                {
                    System.out.println("2nd line valid...");

                    //only included two line checks for now...
                    //as of now if the first two lines are valid
                    //then print out the remaining lines in the
                    //file...
                    System.out.println(text.nextLine());

                }
                else if(!trim2ndLine.contains(fp100)||!trim2ndLine.contains(fp101)||!trim2ndLine.contains(fp200)||
                        !trim2ndLine.contains(fp201)||!trim2ndLine.contains(fp300)||!trim2ndLine.contains(fp301))
                {
                    System.out.println("invalid 2nd line..." +
                            "...terminating");
                    System.exit(0);
                }
                else
                {
                    System.out.println("no file was selected");
                }

            }//end of inner while
            }//end of outer while 
        }//end of try
                catch (Exception ex)
                {
                    System.out.println(ex.getMessage());
                }   
                finally
                {   
                    try
                    {   //close text while lines remain,
                        //valid or not...
                        if(br != null && text != null){
                            br.close();
                            text.close();
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }//end of finally 
        System.out.println("end of file successfully reached...");
    }//end of approve option
}//end of method 




public static void main(String[] args) throws    Exception
{
    Simplified mn = new Simplified();
    mn.readLines();
}//end of main

}//end of Simplified.java 

底线是,无论源代码中的位置如何,也无论 Scanner 和 BufferedReader 对象的类型转换如何,我总是会得到 CCE。任何帮助都会是巨大的。先感谢您。

最佳答案

  1. JFileChooser.getSelectedFile返回 File ,我不知道你为什么想把它包装在 Comparable<File> 中为了??文件本身实现Comparable .
  2. Scanner将接受File作为输入。虽然我没有使用 Scanner 的经验API,我认为你不需要BufferedReader ,只需创建 ScannerFile因为它的来源应该足以让你运行。

他是一个你可以尝试的快速测试。

  1. 为您自己创建一个简单的文本文件,其中包含您需要测试的内容。
  2. 创建一个简单的Class只有 public static void main(String args[]) {...}方法。

main方法尝试类似...

Scanner scanner = new Scanner(new File("path/to/text/file/text.txt"));
while (scanner.hasNext()) {
    System.out.println(scanner.next());
}

从那里开始添加解析逻辑。

关于java - JFileChooser和.txt文件解析问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12630563/

相关文章:

R strsplit 使用正则表达式

c# - 用冒号分割字符串 ( :) and separate the numbers with colon

regex - 使用正则表达式查找多个文件扩展名的命令

c# - 从 int 输入确定回文

c++ - 如何从命令行参数 C++ 创建 std::string

java - 从用户眼中隐藏 HTML 代码的最简单方法是什么?

java - Gradle 错误 :Gradle DSL method not found: 'executeWithoutThrowingTaskFailure()'

c++ - 字符串分配的双重释放或损坏错误

java - 在java中使用字符串初始化的运行时差异是什么?

java - Quartz 调度程序 - 使用同一类的不同作业?