I have a txt file saved in this format:
806PYZnmNaw4h0wh8fyWDQ 0 0 0 0 0 1 0
bvu13GyOUwhEjPum2xjiqQ 0 0 0 1 0 0 0
kDUEcqnK0MrjH9hcYHDKUw 1 0 1 0 0 0 0
806PYZnmNaw4h0wh8fyWDQ 1 0 1 0 0 0 0
bvu13GyOUwhEjPum2xjiqQ 0 1 1 1 1 0 0
tvCT2yT3bLlpU2crUt0zJw 1 0 0 1 0 0 0
806PYZnmNaw4h0wh8fyWDQ 1 1 1 0 0 0 0
9Ify25DK87s5_u2EhK0_Rg 0 0 0 1 0 0 0
bvu13GyOUwhEjPum2xjiqQ 0 1 0 1 0 0 0
806PYZnmNaw4h0wh8fyWDQ 1 0 0 0 0 0 0
zk0SnIEa8ju2iK0mW8ccRQ 0 0 0 0 1 0 0
AMuyuG7KFWJ7RcbT-eLWrQ 0 0 0 1 0 0 0
Now I need to loop through this input file and save a sorted and rearranged output file based on first encoded value which can occur more than once in the input file? For eg in this example file, I have 806PYZnmNaw4h0wh8fyWDQ
more than once in random places.
This is so far I tried: private static final String Path = "newuserfeature.txt";
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
List<String> uniquelist = new ArrayList<String>();
try {
Scanner unique = new Scanner(new FileReader(Path));
while (unique.hasNextLine()) {
String userUnique = unique.nextLine();
uniquelist.add(userUnique);
}
Iterator<String> it = uniquelist.iterator();
while (it.hasNext()) {
String user = it.next();
int a = 0;
int b = 0;
int c = 0;
int d = 0;
int e = 0;
int f = 0;
int g = 0;
Iterator<String> it2 = list.iterator();
while (it2.hasNext()) {
String[] y = it2.next().toString().split(" ");
if (user.equalsIgnoreCase(y[0])) {
int a1 = Integer.parseInt(y[1]);
int b1 = Integer.parseInt(y[2]);
int c1 = Integer.parseInt(y[3]);
int d1 = Integer.parseInt(y[4]);
int e1 = Integer.parseInt(y[5]);
int f1 = Integer.parseInt(y[6]);
int g1 = Integer.parseInt(y[7]);
if (a1 == 1) {
a = a1;
}
if (b1 == 1) {
b = b1;
}
if (c1 == 1) {
c = c1;
}
if (d1 == 1) {
d = d1;
}
if (e1 == 1) {
e = e1;
}
if (f1 == 1) {
f = f1;
}
}
}
System.out.println(user + " " + a + " " + b + " " + c + " " + d
+ " " + e + " " + f + " " + g + "\n");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
If you are only sorting the lines by the first field which happens to be a string, you can you just do:
Path oldFile = Paths.get("/path/to/my/file");
Path newFile = Paths.get("/path/to/my/newFile");
List<String> lines = Files.readAllLines(oldFile);
Collections.sort(lines);
Files.write(newFile, lines);
which:
1: load all lines in a list of strings,
2: sort by string (which is what you want at the end of the day)
3: store the lines in another file
As you are doing a string sorting by the first field, you don't need to break down each line into its columns.
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.