Skip to content
Advertisement

Read string value including spaces : Java

I need to read space-separated values from a file that is separated by a colon.

My file has this data –

Name : User123
DOB : 1/1/1780
Application Status : Not approved yet

Current implementation: I am copying all the values after delimiter (colon in my case) to a new file and reading values from the new file accordingly.

While copying entries to new file spaces are being ignored. In the above file “Not approved yet” is saved as only “Not”. How can I get the complete line? Here is my code –

String regex = "\b(Name |DOB | Application Status )\s*:\s*(\S+)";
        
Pattern p = Pattern.compile(regex);
try (
        BufferedReader br = new BufferedReader(new FileReader("<file to read data>"));
        BufferedWriter bw = new BufferedWriter(new FileWriter("<copy the new file here>"))) {
    String line;
          
    while ((line = br.readLine()) != null) {
        Matcher m = p.matcher(line);
        if (m.find())
            bw.write(m.group(2) + 'n');
    }
}
        
String st;
int count = -1;
String[] data = new String[100];
        
File datafile =new File("<new file where data is copied>");   
        
try {
    Scanner sc = new Scanner(datafile);

    while(sc.hasNextLine()) {
        data[++count] = sc.nextLine();
    }
} catch(Exception e) {
    System.out.println(e);
}

Advertisement

Answer

This \S+ in regex "\b(Name |DOB | Application Status )\s*:\s*(\S+)"; gets only non-white space charcters. So it terminates after seeing space after "Not" value. Inorder to get full value after ":" change the \S+ to .* which gets any character except newline. So the regex becomes like this "\b(Name |DOB | Application Status )\s*:\s*(.*)". It gets all space after the value so trim the value before using it. So your code becomes like this

String regex = "\b(Name |DOB | Application Status )\s*:\s*(.*)";

Pattern p = Pattern.compile(regex);
try (BufferedReader br = new BufferedReader(new FileReader("<file to read data>"));
     BufferedWriter bw = new BufferedWriter(new FileWriter("<copy the new file here>"))) 
{
    String line;
  
    while ((line = br.readLine()) != null) {
        Matcher m = p.matcher(line);
        if (m.find())
            bw.write(m.group(2) + 'n');
    }
}

String st;
int count = -1;
String[] data = new String[100];

File datafile =new File("<new file where data is copied>");   

try
{
    Scanner sc = new Scanner(datafile);
    while(sc.hasNextLine())
    {
        data[++count] = sc.nextLine().trim();
    }
}
catch(Exception e)
{
    System.out.println(e);
}
Advertisement