在Java中,使用Scanner,有没有办法在CSV文件中找到特定的字符串,将其用作列标题并返回其下的所有值?

问题描述 投票:0回答:1

我试图在 csv 文档中找到字符串“5464”,然后让它返回该字符串下的所有值(从行开头开始的分隔符数量相同),直到到达列表末尾(没有更多值)在专栏中)。任何帮助将不胜感激。

import javax.swing.JOptionPane;
public class SearchNdestroyV2 {


    private static Scanner x;


    public static void main(String[] args)  {
        String filepath = "tutorial.txt";
        String searchTerm = "5464"

        readRecord(searchTerm,filepath);
    }

    public void readRecord(String searchTerm, String filepath)
    {
        boolean found = false;
        String ID = ""; String ID2 = ""; String ID3 = "";

    }
        try 
        {
            x = new Scanner(new File(filepath));
            x.useDelimeter("[,\n]");

            while(x.hasNext() && !found )
            {
                ID = x.next();
                ID2 = x.nextLine();
                ID3 = x.nextLine();

                if(ID.equals(searchTerm))
                {
                    found = true;
                }

            }

            if (found)
            {
                JOptionPane.showMessageDialog(null,"ID: " + ID + "ID2: " + ID2 + "ID3: "+ID3);
            }
        }   
            else
            {
                JOptionPane.showMessageDialog(null, "Error:");
            }
        catch(Exception e)
        {

        }
    {  
}

java csv java.util.scanner
1个回答
0
投票

我不太确定你的意思。我读你的问题的方式:

您想要查找包含在逗号 (,) 分隔的 CSV 文件中的特定列中的特定字符串 (“5464”)。如果找到此特定字符串(搜索词),则从该位置检索其余 CSV 文件记录的同一列中包含的所有其他值。方法如下:

import java.io.File;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;

public class SearchNDestroyV2 {

    private Scanner fileInput;


    public static void main(String[] args)  {
        // Do this if you don't want to deal with statics
        new SearchNDestroyV2().startApp(args);
    }

    private void startApp(String[] args) {
        String filepath = "tutorial.txt";
        String searchTerm = "5464";

        readRecord(searchTerm, filepath);
    }

    public void readRecord(String searchTerm, String filepath) {
        try {
            fileInput = new Scanner(new File(filepath));
       
            // Variable to hold each file line data read.
            String line;         
        
            // Used to hold the column index value to 
            // where the found search term is located.
            int foundColumn = -1;
        
            // An ArrayList to hold the column values retrieved from file.
            ArrayList<String> columnList = new ArrayList<>();
        
            // Read file to the end...
            while(fileInput.hasNextLine()) {
                // Read in file - 1 trimmed line per iteration
                line = fileInput.nextLine().trim(); 
            
                //Skip blank lines (if any).
                if (line.equals("")) {
                    continue;
                }
            
                // Split the curently read line into a String Array 
                // based on  the comma (,) delimiter
                String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.
            
                // Iterate through the lineParts array to see if any 
                // delimited portion equals the search term.
                for (int i = 0; i < lineParts.length; i++) {
                    /* This IF statement will always accept the column data and
                       store it if the foundColumn variable equals i OR the current
                       column data being checked is equal to the search term. 
                       Initially when declared, foundColumn equals -1* and will 
                       never equal i unless the search term is indeed found. */
                    if (foundColumn == i || lineParts[i].equals(searchTerm)) {
                        // Found a match
                        foundColumn = i;                // Hold the column index number of the found item.
                        columnList.add(lineParts[i]);   // Add the found item to the List.
                        break;                          // Get out of this loop. Don't need it anymore for this line.    
                    }
                }    

            }

            if (foundColumn != -1) {
                System.out.println("Items Found:" + System.lineSeparator() + 
                                   "============");
                for (String str : columnList) {
                    System.out.println(str);
                }
            }
            else {
                JOptionPane.showMessageDialog(null, "Can't find the Search Term: " + searchTerm);
            }
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }

    }
}

但是,如果您想要搜索 CSV 文件,并且一旦任何特定列等于搜索词(“5464”),则只需存储包含该搜索词的 CSV 行(其所有数据列)即可。方法如下:

import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JOptionPane;


public class SearchNDestroyV2 {

    /* A JFrame used as Parent for displaying JOptionPane dialogs.
       Using 'null' can allow the dialog to open behind other open
       applications (like the IDE). This ensures that it will be
       displayed above all other applications at center screen.  */
    JFrame iFRAME = new JFrame();                  
    {
        iFRAME.setAlwaysOnTop(true);
        iFRAME.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        iFRAME.setLocationRelativeTo(null);
    }

    public static void main(String[] args) {
        // Do this if you don't want to deal with statics
        new SearchNDestroyV2().startApp(args);
    }

    private void startApp(String[] args) {
        String filepath = "tutorial.txt";
        String searchTerm = "5464";
    
        ArrayList<String> recordsFound = readRecord(searchTerm, filepath);

        /* Display any records found where a particular column 
           matches the Search Term.     */
        if (!recordsFound.isEmpty()) {
            System.out.println("Records Found:" + System.lineSeparator()
                    + "==============");
            for (String str : recordsFound) {
                System.out.println(str);
            }
        }
        else {
            JOptionPane.showMessageDialog(iFRAME, "Can't find the Search Term: " + searchTerm);
            iFRAME.dispose();
        }
    }

    /**
     * Returns an ArrayList (of String) of any comma delimited CSV file line
     * records which contain any column matching the supplied Search Term.<br>
     *
     * @param searchTerm (String) The String to search for in all Record
     *                   columns.<br>
     *
     * @param filepath   (String) The CSV (or text) file that contains the data
     *                   records.<br>
     *
     * @return ({@code ArrayList<String>}) An ArrayList of String Type which
     *         contains the file line records where any particular column
     *         matches the supplied Search Term.
     */
    public ArrayList<String> readRecord(String searchTerm, String filepath) {
        // An ArrayList to hold the line(s) retrieved from file 
        // that match the search term.
        ArrayList<String> linesList = new ArrayList<>();

        // Try With Resourses used here to auto-close the Scanner reader.
        try (Scanner fileInput = new Scanner(new File(filepath))) {
            // Variable to hold each file line data read.
            String line;

            // Read file to the end...
            while (fileInput.hasNextLine()) {
                // Read in file - 1 trimmed line per iteration
                line = fileInput.nextLine().trim();

                //Skip blank lines (if any).
                if (line.equals("")) {
                    continue;
                }

                // Split the curently read line into a String Array
                // based on  the comma (,) delimiter
                String[] lineParts = line.split("\\s{0,},\\s{0,}"); // Split on any comma/space situation.

                // Iterate through the lineParts array to see if any
                // delimited portion equals the search term.
                for (int i = 0; i < lineParts.length; i++) {
                    if (lineParts[i].equals(searchTerm)) {
                        // Found a match
                        linesList.add(line);   // Add the found line to the List.
                        break;                 // Get out of this loop. Don't need it anymore for this line.
                    }
                }
            }
        }
        catch (FileNotFoundException ex) {
            System.out.println(ex.getMessage());
        }

        return linesList;  // Return the ArrayList
    }
}

请尝试注意两个代码示例之间的差异。特别是文件读取器(Scanner对象)如何关闭等

© www.soinside.com 2019 - 2024. All rights reserved.