Java:将 String[] 数组元素分配给 String?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/917735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 21:02:48  来源:igfitidea点击:

Java: assign String[] array element to a String?

javaarraysstring

提问by phill

I'm pretty new at this, and this is probably a pretty obvious answer. In my csv script, i'm trying to figure out how to read a csv file using the CSVReader class and write to a new csv file. The error is telling me writeNext(java.lang.String[]) cannot be applied to (java.lang.String). I've tried using a direct assignment and getString() method however nothing works. Any ideas?

我对此很陌生,这可能是一个非常明显的答案。在我的 csv 脚本中,我试图弄清楚如何使用 CSVReader 类读取 csv 文件并写入新的 csv 文件。错误告诉我 writeNext(java.lang.String[]) 不能应用于 (java.lang.String)。我试过使用直接赋值和 getString() 方法,但没有任何效果。有任何想法吗?

I have the following code: UPDATED

我有以下代码: 更新

public static void main(String[] args) throws IOException {
    //read csv file
    CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));

    //write to csv file 
    CSVWriter writer2 = new CSVWriter(new FileWriter("output.csv"), '\t');

    String [] nextLine;
    while ((nextLine = reader.readNext()) != null) {
        System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
        String[] newRow = new String[] {nextLine[0],nextLine[2], nextLine[1]};
    }

    //writer2.writeNext(entries);
    writer2.writeAll(newRow);
    writer2.close();

}

Error: c:\java\examples\ETHImport.java:46: cannot find symbo symbol : variable newRow location: class ETHImport writer2.writeAll(newRow);

错误:c:\java\examples\ETHImport.java:46:找不到符号符号:变量 newRow 位置:类 ETHImport writer2.writeAll(newRow);

1 error

1 错误

Thanks in advance.

提前致谢。

回答by Clint

String[] entries = new String[] { "entry1", "entry2"};

It is expecting an array of entries rather than just one String. If you are following this example http://opencsv.sourceforge.net/notice that

它需要一个条目数组,而不仅仅是一个字符串。如果您正在关注此示例http://opencsv.sourceforge.net/ 请注意

String[] entries = "first#second#third".split("#");

the split call at the end results in a String[].

最后的拆分调用会产生一个 String[]。

for your code:

对于您的代码:

public static void main(String[] args) throws IOException {
        //read csv file
        CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));

        //write to csv file 
        CSVWriter writer2 = new CSVWriter(new FileWriter("output.csv"), '\t');

        String [] nextLine;
        while ((nextLine = reader.readNext()) != null) {
                writer2.writeNext( new String[] {nextLine[0],nextLine[2], nextLine[1]});
        }


        writer2.close();

}

回答by jjnguy

To easily put a Stringinto a String[]use:

轻松地将 aString投入String[]使用:

String[] entriesArr = new String[]{ entries };

or the shortcut

或捷径

String[] entriesArr = { entries };

Now entriesArris a String[]containing one element, entries.

现在entriesArr是一个String[]包含一个元素,entries

回答by Jon Skeet

You need a string array, not a single string. Are you really sure you want to pull all the values into a single string to start with? I'd expect writeNextto write a single line based on the string values you give it, with itputting in the commas etc. After all, it's a CsvWriter- it should be doing the comma separating.

您需要一个字符串数组,而不是单个字符串。您真的确定要将所有值拉到一个字符串中开始吗?我期望writeNext编写一个基于你给它的字符串值单行,与在逗号等投入毕竟,这是一个CsvWriter-它应该做的逗号分隔。

It looks to me like the writeAllmethod you're already using does what you want it to, and writeNextwill just write a single line... what are you trying to achieve that writeAlldoesn't do for you? Why do you need to read it line by line and construct entriesin the first place? Can't you just call:

在我看来,writeAll您已经在使用的方法可以满足您的需求,并且writeNext只会写一行……您想要实现的目标writeAll对您不起作用吗?为什么需要逐行阅读并entries首先构建?你不能只是打电话:

writer2.writeAll(allElements);

My guess is that's going to write a tab-separated file though, given how writer2is constructed.

我的猜测是,鉴于其构造方式,这将编写一个制表符分隔的文件writer2

EDIT: Given the additional information in the comments, I suspect you want to:

编辑:鉴于评论中的其他信息,我怀疑您想要:

  • Open a CsvReader
  • Open a CsvWriter(with an appropriate Writerand ;as the constructor arguments)
  • Loop reading a line at a time as a string array (using CsvReader.readNext()), creating a new string array for the output, and then calling CsvWriter.writeNext()to write that string array out to the file.
  • Close the CsvReaderand CsvWriterin finally blocks (so they'll still get closed if anything goes wrong)
  • 打开一个 CsvReader
  • 打开一个CsvWriter(使用适当的Writer;作为构造函数参数)
  • 循环读取一行作为字符串数组(使用CsvReader.readNext()),为输出创建一个新的字符串数组,然后调用CsvWriter.writeNext()将该字符串数组写入文件。
  • 关闭CsvReaderCsvWriterin finally 块(所以如果出现任何问题,它们仍然会被关闭)

Building the new string array from the existing one would be something like (following your example):

从现有的字符串数组构建新的字符串数组将类似于(按照您的示例):

String[] newRow = new String[] { oldRow[0], oldRow[2], oldRow[1] };

That would basically just keep the first three columns, switching round the second and third ones. If you need other columns, just change it in the same kind of way.

这基本上只保留前三列,切换第二和第三列。如果您需要其他列,只需以相同的方式更改它。

Note that I wouldn'trecommend using FileWriterto write to a file - use a FileOutputStreamand an OutputStreamWriterchained onto it, as this lets you set the character encoding instead of using the platform default one.

请注意,我建议使用FileWriter写入文件 - 使用 aFileOutputStream和一个OutputStreamWriter链接到文件上,因为这可以让您设置字符编码而不是使用平台默认编码。

回答by Stephan

writer.writeNext(String[]) is looking for an array that it will then write as "[0],[1],[2]"

writer.writeNext(String[]) 正在寻找一个数组,然后将其写为“[0],[1],[2]”

Since you are storing the entire csv file as one string, you need to split that string backup. Really you should instead not combine every item into one string but instead store it as an array of strings representing each individual line in the csv file.

由于您将整个 csv 文件存储为一个字符串,因此您需要拆分该字符串备份。实际上,您不应该将每个项目组合成一个字符串,而是将其存储为代表 csv 文件中每一行的字符串数组。