How can you pick one line from a text file and transform it into an array object?

一笑奈何 提交于 2019-12-11 02:45:09

问题


Okay this is code and I need to somehow take a line from the textfile and transform into an array object. like p[0] = "asdasdasd"

public class Patient2 {
    public static void main(String args[])
    {

        int field = 0;
        String repeat = "n";
        String repeat1 = "y";
        Scanner keyIn = new Scanner(System.in);



        // FILE I/O
        try{
              // Open the file that is the first 
              // command line parameter
              FileInputStream fstream = new FileInputStream("Patient.txt");
              BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
              String strLine;
              //Read File Line By Line
              while ((strLine = br.readLine()) != null)   {
              // Print the content on the console
              System.out.println (strLine);
              }
              //Close the input stream
              in.close();
                }catch (Exception e){//Catch exception if any
              System.err.println("Error: " + e.getMessage());
              }
        ArrayList<Patient1> patients=new ArrayList<Patient1>();
        Patient1 p =new Patient1();
        //set value to the patient object
        patients.add(p);
        System.out.println(p);
    }
}

回答1:


Instead of printing it to console you can add it to List<String>

List<String> lines = new ArrayList<String>();
while ((strLine = br.readLine()) != null)   {
   // Print the content on the console
   System.out.println (strLine);
    lines.add(strLine)
}

Note: your code can be much cleaner, you can handle closing resources in finally




回答2:


Just use an ArrayList<String> with add(strline);
and use toArray(new String []) to get the array after input stream has been closed.

 ArrayList<String> list = new ArrayList<String>();
 ...

 while ((strLine = br.readLine()) != null) {
    list.add(strLine);
 }
 ... 

 String [] s = list.toArray(new String []);


来源:https://stackoverflow.com/questions/9090897/how-can-you-pick-one-line-from-a-text-file-and-transform-it-into-an-array-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!