简体   繁体   中英

How to read a multiple String values from text line and store them to a String variable(java)

I want to read line by line from a text file in java, one line consist of 4 fields but one field can contain multiple words, For Ex.: I have this line: Screen Commercial Problem with product

How can I store this three fields of my line into 3 String variables in java?

var1 -> "Screen"
var2 -> "Commercial"
var3 -> "Problem with product"

This splits the input. Use System.in instead of inputStream if reading from standard input:

BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = in.readLine()) != null) {
    String[] split = line.split(" ", 3);
    String var1 = split[0]; String var2 = split[1]; String var3 = split[2];
    // do whatever is needed...
}

Ideally, you'll want to use some specific character to indicate the breaks between fields. For example, Screen|Commercial|Problem with product . Then you could write code that reads the entire line as input and then divides it into substrings. For example:

File yourFile = new File(/*file path goes here*/);
Scanner sc = new Scanner(yourFile);
String input;
String var1;
String var2;
String var3;
int breakIndex;

while (sc.hasNextLine()) {
    input = sc.nextLine();
    breakIndex = input.indexOf("|");
    var1 = input.substring(0, breakIndex);
    input = input.substring(breakIndex+1);
    breakIndex = input.indexOf("|");
    var2 = input.substring(0, breakIndex);
    var3 = input.substring(breakIndex+1);
    // do whatever it is you plan to do with those variables here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM