Java CSV 文件操作

发布于 2024-11-07 11:01:42 字数 182 浏览 1 评论 0原文

我有以下示例 CSV 文件,

rc,u,s,ui,gh
m,1,8,0,12
n,3,0,0,7
d,1,1,8,0

我想读取此 CSV 文件并按其名称(例如 s)获取列。将获取的列减去一些值并更新 CSV 文件中的该列。

有没有一种简单的方法可以用Java实现呢?

I have following sample CSV file

rc,u,s,ui,gh
m,1,8,0,12
n,3,0,0,7
d,1,1,8,0

I want to read this CSV file and get column by its name (e.g., s). subtract fetched column by some values and update that column in the CSV file.

Is there an easy way to do it in Java?

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

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

发布评论

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

评论(6

烟─花易冷 2024-11-14 11:01:42

在 PHP 中这很容易,您可以使用 fgetcsv 函数 http://php.net/manual /en/function.fgetcsv.php

添加示例

    <?php

    $inHandle= fopen("input.csv", "r");

    $text = "";
    $someVar = array(1, 2, 3, 4);           // for subtracting 1 from col1 2 from col2 ...

    while ( ( $data = fgetcsv($inHandle) ) !== FALSE) 
    {
    $text  = $text  . $data[0];

    for ($i= 1; $i < count($data);  $i++) 
    {

        if($i==0)
            $text =  $text .  $data[$i] . ", ";
        else
            $text =  $text .  ( $data[$i] - $someVar[$i -1] ) . " , ";
    }
       $text =  $text . " \n";
    }

    fclose($inHandle);

    $outHandle = fopen('output.csv', 'w');

    fwrite($outHandle , $text );

    fclose($outHandle );
    ?>

It is quite easy in PHP, you can use fgetcsv function http://php.net/manual/en/function.fgetcsv.php

Added Sample

    <?php

    $inHandle= fopen("input.csv", "r");

    $text = "";
    $someVar = array(1, 2, 3, 4);           // for subtracting 1 from col1 2 from col2 ...

    while ( ( $data = fgetcsv($inHandle) ) !== FALSE) 
    {
    $text  = $text  . $data[0];

    for ($i= 1; $i < count($data);  $i++) 
    {

        if($i==0)
            $text =  $text .  $data[$i] . ", ";
        else
            $text =  $text .  ( $data[$i] - $someVar[$i -1] ) . " , ";
    }
       $text =  $text . " \n";
    }

    fclose($inHandle);

    $outHandle = fopen('output.csv', 'w');

    fwrite($outHandle , $text );

    fclose($outHandle );
    ?>
软的没边 2024-11-14 11:01:42
String line;
BufferedReader br = new BufferedReader(new FileReader("path_to_your_file"));

while ((line = br.readLine()) != null) { 
       StringTokenizer tokenizer = new StringTokenizer(line, ",");

       while(tokenizer.hasMoreTokens()) {
              String token = tokenizer.nextToken(); 
       } 
}

这样你就可以获得逗号分隔的令牌。对它们执行您想要的操作,然后查看 BufferedWriter 类来存储值。

String line;
BufferedReader br = new BufferedReader(new FileReader("path_to_your_file"));

while ((line = br.readLine()) != null) { 
       StringTokenizer tokenizer = new StringTokenizer(line, ",");

       while(tokenizer.hasMoreTokens()) {
              String token = tokenizer.nextToken(); 
       } 
}

This way you can get your comma separated tokens. Do what you want with them and then, have a look at BufferedWriter class to store back the values.

等风也等你 2024-11-14 11:01:42

据我所知,没有“简单”的方法可以做到这一点,至少使用标准 Java API 是这样。循环可能是这里唯一的选择。

然而,还有其他语言可以使这种事情相对简单。 R(免费且开源)是一种出色的数据操作语言。

As far as I know, there is no 'easy' way of doing this, at least with the standard Java API. Looping is probably going to be the only option here.

There are, however, other languages which make this kind of thing relatively simple. R (freely available and open source) is a great language for data manipulation.

梦里寻她 2024-11-14 11:01:42

在 PHP 中,您可以尝试这样的操作:

<?php
function csv2PhpArray($sFile,$sSeparator = ';'){
$arrCsv;
$arrCsvKeys;
$i = 0;
    if (($handle = fopen($sFile, "r")) !== false) {
        while (($arrRow = fgetcsv($handle, 1000, $sSeparator)) !== false) {
            //Each row
            $nLenRow = count($arrRow);
            for ($j=0; $j < $nLenRow; $j++) {
                if($i==0){
                    $arrCsvKeys[] = $arrRow[$j];
                }else{
                    $arrCsv[$arrCsvKeys[$j]][] = $arrRow[$j];
                }
            }
            if($i==0) $i++;
        }
        fclose($handle);
    }
    return $arrCsv;
}
function updateCsv($arrCsv,$sFile,$sSeparator = ';'){
    $arrCsvKeys = array_keys($arrCsv);
    $i = 0;
    $nMaxKeys = count($arrCsvKeys);
    $nMax  = count($arrCsv[$arrCsvKeys['0']]);
    $arrInput;
    for($k=0;$k<$nMaxKeys;$k++){
        $arrInput[$i][$k] = $arrCsvKeys[$k];
    }
    for($j=0;$j<$nMax;$j++){
        $i++;
        for($k=0;$k<$nMaxKeys;$k++){
            $arrInput[$i][$k] = $arrCsv[$arrCsvKeys[$k]][$j];
        }
    }

    $nMax  = count($arrInput);
    $fp = fopen($sFile, 'w');
    for($i=0;$i<$nMax;$i++){
        fputcsv($fp, $arrInput[$i]);
    }

    fclose($fp);
}

$arrCsv = csv2PhpArray('file.csv',';');
echo '<pre>';
var_dump($arrCsv);
echo '</pre>';
$nMax = count($arrCsv['s']);
for($i=0;$i<$nMax;$i++){
    $arrCsv['s'][$i]= intval($arrCsv['s'][$i])+10;
}
echo '<pre>';
var_dump($arrCsv);
echo '</pre>';
updateCsv($arrCsv,'file2.csv',';');
echo '<pre>';
var_dump(csv2PhpArray('file2.csv',';'));
echo '</pre>';
?>

我放置了两个文件(file.csv 和 file2.csv)来查看更新结果。

我看到你将答案更改为仅java,但我希望这可以帮助你。

In PHP you could try with something like this:

<?php
function csv2PhpArray($sFile,$sSeparator = ';'){
$arrCsv;
$arrCsvKeys;
$i = 0;
    if (($handle = fopen($sFile, "r")) !== false) {
        while (($arrRow = fgetcsv($handle, 1000, $sSeparator)) !== false) {
            //Each row
            $nLenRow = count($arrRow);
            for ($j=0; $j < $nLenRow; $j++) {
                if($i==0){
                    $arrCsvKeys[] = $arrRow[$j];
                }else{
                    $arrCsv[$arrCsvKeys[$j]][] = $arrRow[$j];
                }
            }
            if($i==0) $i++;
        }
        fclose($handle);
    }
    return $arrCsv;
}
function updateCsv($arrCsv,$sFile,$sSeparator = ';'){
    $arrCsvKeys = array_keys($arrCsv);
    $i = 0;
    $nMaxKeys = count($arrCsvKeys);
    $nMax  = count($arrCsv[$arrCsvKeys['0']]);
    $arrInput;
    for($k=0;$k<$nMaxKeys;$k++){
        $arrInput[$i][$k] = $arrCsvKeys[$k];
    }
    for($j=0;$j<$nMax;$j++){
        $i++;
        for($k=0;$k<$nMaxKeys;$k++){
            $arrInput[$i][$k] = $arrCsv[$arrCsvKeys[$k]][$j];
        }
    }

    $nMax  = count($arrInput);
    $fp = fopen($sFile, 'w');
    for($i=0;$i<$nMax;$i++){
        fputcsv($fp, $arrInput[$i]);
    }

    fclose($fp);
}

$arrCsv = csv2PhpArray('file.csv',';');
echo '<pre>';
var_dump($arrCsv);
echo '</pre>';
$nMax = count($arrCsv['s']);
for($i=0;$i<$nMax;$i++){
    $arrCsv['s'][$i]= intval($arrCsv['s'][$i])+10;
}
echo '<pre>';
var_dump($arrCsv);
echo '</pre>';
updateCsv($arrCsv,'file2.csv',';');
echo '<pre>';
var_dump(csv2PhpArray('file2.csv',';'));
echo '</pre>';
?>

I put two files (file.csv and file2.csv) to see the update results.

I see you change the answer to only java, but I hope this can be help you.

美人骨 2024-11-14 11:01:42

您可以使用 JEzCSV 来读取或写入 CSV 文件,可以读取代码,是开源的

You can use JEzCSV for read or write CSV file, can you can read the code, is open source

你的背包 2024-11-14 11:01:42

您可能对我发布到 GitHub 的代码感兴趣,该代码读取 CSV,将 CSV 放入 POJO,然后从 POJO 写入 CSV 文件。这将使用 POJO 修改原始 CSV,并将所需的新列写入新的 CSV 文件。

https://github.com/Blue4570/CsvAppender

公共类 CsvWriter {

private File csvFile;
private String delimiter;
static final String NEW_FILE_LOCATION_AND_NAME = "<LOCATION_AND_NAME_OF_YOUR_FILE_HERE";


public CsvWriter(String delimiter) {
    this.csvFile = new File(getClass().getClassLoader().getResource("csv/TestCsv.txt").getFile());
    this.delimiter = delimiter;
}

public void writeFile() {
    List<NewTable> tableList = readFile(csvFile);
    try(FileWriter writer = new FileWriter(NEW_FILE_LOCATION_AND_NAME)) {
        writer.append("ID$FirstName$LastName").append("\n");
        tableList.forEach(table -> {
            try {
                writer.append(table.getId()).append(delimiter);
                writer.append(table.getFirstName()).append(delimiter);
                writer.append(table.getLastName());
                writer.append("\n");
            } catch (IOException e) {
                System.out.println("Unable to write new File");
                e.printStackTrace();
            }
        });
    } catch(IOException e) {
        System.out.println("Unable to write new file");
    }
}

private List<NewTable> readFile(File csvFile) {
    List<NewTable> tableList = new ArrayList<>();
    try (InputStream inputFS = new FileInputStream(csvFile);
         BufferedReader br = new BufferedReader(new InputStreamReader(inputFS))
    ) {
        // skip the header of the csv
        tableList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());

    } catch (IOException e) {
        System.out.println("Error reading file");
    }
    return tableList;
}

private Function<String, NewTable> mapToItem = (line) -> {
    Optional<NewTable> newTable = Optional.empty();
    if (line != null) {
        String[] p = line.split("\\$");
         newTable = Optional.of(new NewTable(p[0], p[1]));
    }
    return newTable.orElseGet(NewTable::new);
};

}

You may be interested in the code I have posted to GitHub which reads CSV, puts the CSV into a POJO, and then writes from the POJO to a CSV file. This modifies the original CSV using the POJO and writes the new columns you need to a new CSV file.

https://github.com/Blue4570/CsvAppender

public class CsvWriter {

private File csvFile;
private String delimiter;
static final String NEW_FILE_LOCATION_AND_NAME = "<LOCATION_AND_NAME_OF_YOUR_FILE_HERE";


public CsvWriter(String delimiter) {
    this.csvFile = new File(getClass().getClassLoader().getResource("csv/TestCsv.txt").getFile());
    this.delimiter = delimiter;
}

public void writeFile() {
    List<NewTable> tableList = readFile(csvFile);
    try(FileWriter writer = new FileWriter(NEW_FILE_LOCATION_AND_NAME)) {
        writer.append("ID$FirstName$LastName").append("\n");
        tableList.forEach(table -> {
            try {
                writer.append(table.getId()).append(delimiter);
                writer.append(table.getFirstName()).append(delimiter);
                writer.append(table.getLastName());
                writer.append("\n");
            } catch (IOException e) {
                System.out.println("Unable to write new File");
                e.printStackTrace();
            }
        });
    } catch(IOException e) {
        System.out.println("Unable to write new file");
    }
}

private List<NewTable> readFile(File csvFile) {
    List<NewTable> tableList = new ArrayList<>();
    try (InputStream inputFS = new FileInputStream(csvFile);
         BufferedReader br = new BufferedReader(new InputStreamReader(inputFS))
    ) {
        // skip the header of the csv
        tableList = br.lines().skip(1).map(mapToItem).collect(Collectors.toList());

    } catch (IOException e) {
        System.out.println("Error reading file");
    }
    return tableList;
}

private Function<String, NewTable> mapToItem = (line) -> {
    Optional<NewTable> newTable = Optional.empty();
    if (line != null) {
        String[] p = line.split("\\$");
         newTable = Optional.of(new NewTable(p[0], p[1]));
    }
    return newTable.orElseGet(NewTable::new);
};

}

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