Learning Java. Trying to open a file read it and choose needed contents to write in another file. My file looks like this:
DESCRIPTION:
TITILE:
TYPE: image
SOURCE: UIUC Library
FORMAT: jpeg
IDENTIFIER: 120034
LATITUDE: 40.109580
LONGITUDE: -88.228378
DESCRIPTION:
TITLE: GSLIS
SUBJECT:
TYPE: image
SOURCE: UIUC Library
FORMAT: jpeg
IDENTIFIER: 120155
LATITUDE: 40.107779
LONGITUDE:-88.231621
I just wrote two pieces of code, one for open and read, one for match the patterns:
package Functions;
import java.io.IOException;
import java.io.FileReader;
import java.io.BufferedReader;
public class readFileLocal {
private String path;
public readFileLocal(String file_path){
path = file_path;
}
public String[] openFile() throws IOException{
FileReader freader = new FileReader (path);
BufferedReader textReader = new BufferedReader (freader);
int numberOfLines = readLines();
String[] textData = new String[numberOfLines];
int i;
for (i=0; i<numberOfLines; i++){
textData[i] = textReader.readLine();
}
textReader.close();
return textData;
}
int readLines() throws IOException{
FileReader file_to_read = new FileReader(path);
BufferedReader lines = new BufferedReader (file_to_read);
String aLine=lines.readLine();
int numberOfLines = 0;
while(aLine != null) {
numberOfLines ++;
}
lines.close();
return numberOfLines;
}
}
I also figured how to search a string in the way I wanted with people's help, as shown below:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ReadLatLong
{
public ReadLatLong(){
String line = "IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS IDENTIFIER: 115956 LATITUDE: 40.104730 LONGITUDE: -88.228798 DATE RIGHTS";
String pattern = "IDENTIFIER:\\s(\\d*)\\sLATITUDE:\\s(\\d*\\.?\\d*)\\sLONGITUDE:\\s(.*?)\\s";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);
while (m.find()) {
System.out.println("Image: " + m.group(1)+"|"+m.group(2)+"|"+m.group(3));
}
}
}
Now I wonder how to search the whole file to grab all identifier, latitude, longitude, and put them all out like this: 120034 | 40.109580 | -88.228378 120155 | 40.107779 | -88.231621 Thanks in advance.
Aucun commentaire:
Enregistrer un commentaire