2

I was wondering how I would create a java program which reads from a file and assigns variables.

import java.io.*;

public class Reader {
    public static void main(String[] args) {
        String str;
        String time=null;
        try  {
            BufferedReader reader = new BufferedReader(new FileReader("pathfilehere"));
            while((a = reader.readLine()) != null) {
                reader.readLine();
            }
        } catch(FileNotFoundException e){System.out.println("Error: "+e.getMessage());
        } catch(IOException e){System.out.println("Error: "+e.getMessage());
        }
        System.out.println(time);
    }
}

If I have a txt file with a variable "str" and its value is "randomstring", my question is how can I tell my java program to assign this variable from the text file and store it into the java program to use later on?

4

1 回答 1

1
import java.io.*;

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

        BufferedReader reader = null;
        StringBuilder randomstring =  new StringBuilder();
        try  {
             reader = new BufferedReader(new FileReader("file.txt"));


            String line = reader.readLine();
            while(line !=  null) {
                randomstring.append(line + '\n');

                 line = reader.readLine();
            }
        } catch(FileNotFoundException e){System.out.println("Error: "+e.getMessage());
        } catch(IOException e){System.out.println("Error: "+e.getMessage());
        }
        finally{
            try{
                reader.close();
            }catch(Exception E){}
        }
        System.out.println(randomstring.toString());
    }
}
于 2013-09-11T02:43:27.770 回答