java中findcolumn('xx')是找到数据库中的对应列么,java - 在Java中,使用Scanner,是否可以在CSV文件中查找特定的String,将其用作列标题并返回其下的所有值? -...

我不确定您的意思。 我阅读您的问题的方式:

您想要找到一个用逗号(,)分隔的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 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 Coloumn index number of the found item.

columnList.add(lineParts[i]); // Add the found ite 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 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.

*

* @param searchTerm (String) The String to search for in all Record

* columns.

*

* @param filepath (String) The CSV (or text) file that contains the data

* records.

*

* @return ({@code ArrayList}) An ArrayList of String Type which

* contains the file line records where any particular column

* matches the supplied Search Term.

*/

public ArrayList readRecord(String searchTerm, String filepath) {

// An ArrayList to hold the line(s) retrieved from file

// that match the search term.

ArrayList 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

}

}

请尝试注意两个代码示例之间的区别。 特别是如何关闭文件阅读器(扫描仪对象)等。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值