Java read file and store text in an array

前端 未结 7 1861
心在旅途
心在旅途 2020-11-30 06:25

I know how to read a file with Java using Scanner and File IOException, but the only thing I don\'t know is how to store the text in the files as a

7条回答
  •  一向
    一向 (楼主)
    2020-11-30 06:51

    Stored as strings:

    public class ReadTemps {
    
        public static void main(String[] args) throws IOException {
        // TODO code application logic here
    
        // // read KeyWestTemp.txt
    
        // create token1
        String token1 = "";
    
        // for-each loop for calculating heat index of May - October
    
        // create Scanner inFile1
        Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
    
        // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
        // List temps = new LinkedList();
        List temps = new ArrayList();
    
        // while loop
        while (inFile1.hasNext()) {
          // find next line
          token1 = inFile1.next();
          temps.add(token1);
        }
        inFile1.close();
    
        String[] tempsArray = temps.toArray(new String[0]);
    
        for (String s : tempsArray) {
          System.out.println(s);
        }
      }
    }
    

    For floats:

    import java.io.File;
    import java.io.IOException;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.Scanner;
    
    public class ReadTemps {
    
      public static void main(String[] args) throws IOException {
        // TODO code application logic here
    
        // // read KeyWestTemp.txt
    
        // create token1
    
        // for-each loop for calculating heat index of May - October
    
        // create Scanner inFile1
        Scanner inFile1 = new Scanner(new File("KeyWestTemp.txt")).useDelimiter(",\\s*");
    
    
        // Original answer used LinkedList, but probably preferable to use ArrayList in most cases
        // List temps = new LinkedList();
        List temps = new ArrayList();
    
        // while loop
        while (inFile1.hasNext()) {
          // find next line
          float token1 = inFile1.nextFloat();
          temps.add(token1);
        }
        inFile1.close();
    
        Float[] tempsArray = temps.toArray(new Float[0]);
    
        for (Float s : tempsArray) {
          System.out.println(s);
        }
      }
    }
    

提交回复
热议问题