簡體   English   中英

如何同時掃描多個txt文件?

[英]How do I scan multiple txt files at the same time?

我正在學習Java EE,並嘗試根據代碼中列出的選項值掃描多個文本文件。 如果選擇了三個選項之一,它將掃描相應的文本文件並輸出一些信息。

如您所見,我顯然可以忽略一個選項而只掃描一個文件。 我不確定如何根據選擇將代碼調整為切換到其他文件。

我想我將不得不四處移動,例如在實現選項選擇的if語句內移動while循環,然后在文件中掃描ID,這應該不是問題。 我只是從不同的txt文件讀取時傻眼了。

我已經在下面發布了我的代碼,因此您可以了解我要做什么。

我應該創建多個掃描儀並以這種方式實施它還是應該做其他事情?

編輯:感謝一點幫助,我設法使它開始工作。 這是修改后的工作代碼。

<body>
    <%
    String id = request.getParameter("id");        
    String cid = request.getParameter("classID");
    String[] title = {"Name: ", "SSN: ", "Score: "};
    Scanner sc;        
    %>

    Find Your Current Score.
    <%-- Blank space here --%>
    <p></p>
    <%-- Input Forms (Text Field and Button) --%>
    <form action="ScoreFinder.jsp" method="get">
    Employee ID:
    <input type="text" name="id"/> Use SSN Format: xxx-xxx-xxxx
    <p></p>
    Class:
    <select name="classID">
    <option value="CMIS440">CMIS 440</option>
    <option value="CMIS445">CMIS 445</option>
    <option value="CMIS485">CMIS 485</option>
    </select>
    <input type="submit" value="Submit" />
    </form>

    <%
        if (id != null || cid != null) {
            String fileName = "/"+cid.replaceAll(" ", "") + ".txt";
            sc = new Scanner(new File(application.getRealPath(fileName)));
            while(sc.hasNext()) {                
            String line = sc.nextLine();
            String[] split = line.split("[#]");
            if (id.length() == 0) {
                out.println("Please enter an ID number.");
                break;
            }
            if (line.contains(id)) {
                out.println("Class: " + cid);
                %><br><%
                for (int i=0; i<split.length; i++){
                    out.println(title[i]);
                    out.println(split[i]);
                    %><br><%
                }
                break;
            }
            }
        }%>
</body>

假設您列出的JSP的名稱為ScoreFinder.jsp,並且您正在將記錄提交到同一JSP。

您可以從參數id的值創建文本文件的名稱,例如

<body>
    <%
    String id = request.getParameter("id");
    String fileName = "/"+id.replaceAll(" ", "")+".txt"; // avoiding null check of 'id' for simplicity
    Scanner sc = new Scanner(new File(application.getRealPath(fileName)));
    try {
        while(sc.hasNext()) {

    ........
    ........

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM