【问题标题】:how to read a file and store the data in to string array [closed]如何读取文件并将数据存储到字符串数组中[关闭]
【发布时间】:2014-09-12 12:33:45
【问题描述】:

嗨,有一个名为 read.txt 的文件,下面是文件内的数据。

OS:B,A,Linux,Windows 7,Windows     
ARCH:32 Bit,64 Bit    
Browser:Chrome,Firefox,IE   

我想读取文件并希望通过随同
将数据存储到每列的字符串数组中 “:”符号。

示例如下

String a[] = { "A","B","Linux", "Windows 7", "Windows" };    

String b[] = { "32 Bit", "64 Bit"};    

String c[] = { "Chrome", "Firefox" ,"IE"};  

【问题讨论】:

标签: java


【解决方案1】:

一种方法是通过 ReadLine 提取每一行。 一旦我们有一个包含该行的字符串,假设我们有一个“:”作为分隔符,拆分该行。 提取数组的第二个元素并使用“,”作为分隔符进行另一个拆分

【讨论】:

    【解决方案2】:

    使用 apache commons io...

    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    import org.apache.commons.io.FileUtils;
    
    public class StackOverflowExample {
        public static void main(String[] args) throws IOException{
            List<String> lines = FileUtils.readLines(null, "UTF-8");
            List<String[]> outLines = new ArrayList<String[]>();
            for(int i = 0; i < lines.size(); i++){
                String line = lines.get(i);
                outLines.add(line.split("[:,]"));
    
            }
       }
    }
    

    正如已经指出的那样 - 您确实应该包含一个您正在使用的代码示例,该示例没有按照您的预期执行。如果您真的完全不知道该怎么做并且没有代码 - 我不确定这是否会有所帮助。

    【讨论】:

      【解决方案3】:

      以下是您读取文件的方式:

      BufferedReader reader = new BufferedReader("read.txt");
      while((line = reader.readLine()) != null)
      {
          //process line
      }
      

      所以要得到你想要的结果:

      ArrayList<String[]> arrays = new ArrayList<String[]>;
      BufferedReader reader = new BufferedReader("read.txt");
      while((line = reader.readLine()) != null)
      {
          //process line
          line = line.split(":")[1];//get the second part
          arrays.add(line.split(","));//split at "," and save into the ArrayList
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-25
        相关资源
        最近更新 更多