I am currently reading and writing to a text file and I cant figure out a way to sort. I thought I would be able to sort by pattern. I would like to sort a java string array by the pattern (0-9, A-Z, a-z). Basically I would like to ignore non-alphanumeric characters, sort with numbers preceding letters, and capital letters preceding lowercase letters (i.e., 0-9, A-Z, a-z). I would like to remove lines that only have non-alphanumeric characters.
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
// SORT GOES HERE
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
I would likely use something like Collections.sort() at the end and a simple check in the loop:
File f1 = new File(fp);
FileReader fr = new FileReader(f1);
BufferedReader br = new BufferedReader(fr);
List<String> lines = new ArrayList<String>();
String line;
while ((line = br.readLine()) != null) {
count++;
if (!line.matches("[a-zA-Z0-9]+")) {
continue;
}
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isBlank()) {
line = line.substring(yint);
}
if(!line.isBlank()){
line = line.replace(line, count + " " + line + "\n");
lines.add(line);
} else {
lines.add(line);
}
}
fr.close();
br.close();
Collections.sort(lines, (a, b) -> {
String aNum = a.replaceAll("[^a-zA-Z0-9]", "");
String bNum = b.replaceAll("[^a-zA-Z0-9]", "");
return a.compareTo(b);
});
FileWriter fw = new FileWriter(f1);
BufferedWriter out = new BufferedWriter(fw);
for(String s : lines)
out.write(s);
out.flush();
out.close();
EDIT: You can certainly make this work faster/better by quick-checking perhaps in the sort, etc - but generally this is the idea I think
You can't sort the file while you are reading it, in your case it needs to be done before:
// Sort the file
Path initialFile = Paths.get("myFile.txt");
List<String> sortedLines = Files.lines(initialFile)
.sorted()
.collect(Collectors.toList());
// Process the sorted lines
List<String> lines = new ArrayList<String>();
int count=0;
for(String line : sortedLines) {
System.out.println("l: "+line);
count++;
if (line.contains(sx)) {
line = line.replace(line, "");
}
if (yint > 0 && !line.isEmpty()) {
line = line.substring(yint);
}
if (!line.isEmpty()) {
System.out.println("line:"+line);
line = line.replace(line, count + " " + line + "\n");
System.out.println("new line:"+line);
lines.add(line);
} else {
System.out.println("add:"+line);
lines.add(line);
}
}
// Write output file
File f1 = new File("myFile.txt");
try(BufferedWriter out = new BufferedWriter( new FileWriter(f1))){
for (String s : lines)
out.write(s);
}
Try this.
static void sortByAlphaNumeric(String inFile, String outFile) throws IOException {
List<String> lines = Files.readAllLines(Paths.get(inFile)).stream()
.map(line -> new Object() {
String sortKey = line.replaceAll("[^0-9A-Za-z]", "");
String originalLine = line;
})
.filter(obj -> !obj.sortKey.equals(""))
.sorted(Comparator.comparing(obj -> obj.sortKey))
.map(obj -> obj.originalLine)
.collect(Collectors.toList());
Files.write(Paths.get(outFile), lines);
}
Related
I'm currently working on an assignment and I cannot find any clue to remove the headline from the text file and write the rest into an ArrayList. Can someone help me?
ID,Nama,GajiPokok,JmlAbsensi,JmlIzin
2,Peter,5000000,17,3
1,John,4500000,19,1
3,Linda,10000000,13,7
4,Lucy,7000000,20,0
Here is my code:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
try {
String line = in.readLine();
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
in.close();
} catch (IOException e){e.printStackTrace();}
If you want to ignore first line while reading the CSV file then you can simple skip processing of 1st line by calling in.readLine(); twice at the start as shown in below example:
BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"));
String line = in.readLine();
line = in.readLine(); //skip fist line and read second line
String data[];
while (line != null){
data = line.split(",");
Staff s = new Staff(){};
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setjmlhAbsensi(Integer.parseInt(data[3]));
s.setjmlhIzin(Integer.parseInt(data[4]));
s.getID();
s.getNama();
s.getGajiPokok();
s.getjmlhAbsensi();
s.getjmlhIzin();
list_Staff.addAll(Arrays.asList(s));
line = in.readLine();
}
Using skip() method of JAVA 8 Streams:
try(BufferedReader in = new BufferedReader(new FileReader("D:\\" + args[0] + ".txt"))) {
Stream<String> lines = in.lines();
List<Staff> staff = lines.skip(1).map(line -> {
Staff s = new Staff();
String data[] = line.split(",");
s.setID(Integer.parseInt(data[0]));
s.setNama(data[1]);
s.setGajiPokok(Long.parseLong(data[2]));
s.setJmlhAbsensi(Integer.parseInt(data[3]));
s.setJmlhIzin(Integer.parseInt(data[4]));
return s;
}).collect(Collectors.toList());
System.out.println(staff);
}
You can declare the following line twice or initialize integer variable and skip the loop if its zero.
String line = in.readLine();
This solution works.
private void readTextFile(String fileName) throws FileNotFoundException {
BufferedReader in = new BufferedReader(new FileReader(fileName));
Stream<String> stream = in.lines();
List<String> answer = stream.collect(Collectors.toList());
// For Pre-Java8
/*for (int i = 1; i < answer.size(); i++) {
System.out.println(answer.get(i));
}*/
// Split afterwards.
Stream<String> ans = answer.stream().filter(p -> !p.equals(answer.get(0)));
ans.forEach(x -> System.out.println(x));
}
protected synchronized static void getRandomProxy(String srcFile) throws FileNotFoundException {
List<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
words.add(line);
System.out.println(line);
}
int k = 0;
for (int i = 0; i < words.size(); i++) {
k++;
String[] splitted = words.get(i).split(":");
String ip = splitted[0];
String port = splitted[splitted.length - 1];
// System.out.println(k + " " + ip + " * " + port);
}
} catch (IOException iOException) {
} finally {
try {
reader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
I want to get output printed without empty lines .
These are kind of results am getting Like :
result 1.
result 2.
result 3.
i want output like :
result 1.
result 2.
result 3.
without blank lines.
Don't add the String to the list if it's empty :
if(!line.trim().isEmpty()) {
words.add(line);
System.out.println(line);
}
If you still want to add the blank lines to the list but don't display them, just move the condition :
words.add(line);
if(!line.trim().isEmpty())
System.out.println(line);
Doc
Use System.out.print. Note that the file contains a newline char at the end of each line.
If srcFile is created with Notepad, try removing first the carriage return char System.out.print(line.replaceAll("\\r",""))
ArrayList<String> words = new ArrayList<>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(srcFile));
String line;
while ((line = reader.readLine()) != null) {
line = line.trim(); // remove leading and trailing whitespace
if (!line.isEmpty() && !line.equals("")) {
words.add(line);
System.out.println(line);
}
}
I have a text file like this:
Emma,F,20355
Olivia,F,19553
Sophia,F,17327
Ava,F,16286
Isabella,F,15504
Mia,F,14820
Abigail,F,12311
Emily,F,11727
I am trying to remove words after , and also put two lines in one line for every two lines.
For example:
Emma Olivia
Sophia Ava
Isabella Mia
Abigail Emily
The program can do the first part, but I don't know how the program can do the second part. I can split the words and numbers after first ,, but I got stuck how I can can arrange lines.
Here is the code:
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String res;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
res = a[0] + "\n";
writer.write(res);
}
writer.close();
reader.close();
I think I need to create a for loop inside while loop, but I am not sure what to write to count even or odd lines.
Change to to something like this :
int count = 1;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
res = a[0] + count % 2 == 0 ? "\n" : " ";
count++;
writer.write(res);
}
try (
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile))
) {
while (true) {
String line1 = reader.readLine();
if (line1 == null) {
break;
}
writer.write(line1.split(",", 2)[0]);
String line2 = reader.readLine();
if (line2 == null) {
writer.newLine();
break;
}
writer.write(" " + line2.split(",", 2)[0]);
writer.newLine();
}
}
int newLine = 1;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
if (newLine % 2 == 0)
res += a[0] + "\n";
else
res += a[0] + " ";
newLine++;
}
writer.write(res);
Try reading two lines in at the same time if there is a second line left in the reader.
Something like this:
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String[] a;
String[] b;
String res;
while ((currentLine = reader.readLine()) != null) {
a = currentLine.split(",");
if (reader.hasNext()) {
b = reader.readLine().split(",");
res = a[0] + " " + b[0] + "\n";
} else {
res = a[0]+"\n";
}
writer.write(res);
}
writer.close();
reader.close();
As mentioned above, read in two lines at a time. Combine them, then split based on the delimiter (comma) - Should then be easy to write out new format to a text file (Maybe pop the results in a list, then iterate over the list to write it out.
This is not a complete solution, but should be enough for you to get the idea.
// Read two lines at a time
String currentLine = reader.readLine(); //Emma,F,20355
String nextLine = reader.readLine(); //Olivia,F,19553
String combinedLine = currentLine + "," + nextLine;
// split into separate elements
String[] elements = combinedLine.split(",");
List<String> newLines = new ArrayList<>();
newLines.add(elements[0] + " " + elements[3]);
for (final String line : newLines) {
// write to file
writer.write(res);
}
lets say we have a list of array items
ex:- a,b,c,d
which needs to be removed from a file which is full of data , I am missing something can anyone please help me in achieving this , thanks in advance
public static void rmvFromXML(String strFilePath,
String strTmpFilePath) throws IOException {
String currentLine = "";
List<String> list = new ArrayList<String>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
BufferedWriter fileWriter = null;
fileWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(strTmpFilePath)));
while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
System.out.println("Trimmed Line :- " + trimmedLine);
for (String value : list) {
System.out.println("Array Value:- " + value);
if (trimmedLine.equals(value))
continue;
fileWriter.write(trimmedLine + System.getProperty("line.separator"));
}
}
fileWriter.close();
reader.close();
}
you can use regex. so that you wont have to iterate and check whether the
line contains your strings
while ((currentLine = reader.readLine()) != null) {
Pattern removeWords = Pattern.compile("\\b(?:a|b|c|d)\\b\\s*", Pattern.CASE_INSENSITIVE);
Matcher fix = removeWords.matcher(currentLine);
String fixedString = fix.replaceAll("");
}
try doing it with above approach
input :
abcdefg
output
efg
You need to replace provided substrings on each occurrence in lines from file, so replace it with empty spaces:
public static void rmvFromXML(String strFilePath,
String strTmpFilePath) throws IOException {
String currentLine = "";
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
list.add("c");
list.add("d");
BufferedReader reader = new BufferedReader(new FileReader(strFilePath));
BufferedWriter fileWriter = null;
fileWriter = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(strTmpFilePath)));
while ((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
System.out.println("Trimmed Line :- " + trimmedLine);
for (String value : list) {
System.out.println("Array Value:- " + value);
trimmedLine = trimmedLine.replaceAll(value, "");
}
fileWriter.write(trimmedLine + System.getProperty("line.separator"));
}
fileWriter.close();
reader.close();
}
So now for input:
sdfsdf
sdfsdf
sfsdfs
fa
a
b
c
asdasdad
d
asdasd
We get output:
sfsf
sfsf
sfsfs
f
ss
ss
Replace:
for (String value : list) {
System.out.println("Array Value:- " + value);
if (trimmedLine.equals(value))
continue;
fileWriter.write(trimmedLine + System.getProperty("line.separator"));
}
by:
bool found=false:
for (String value : list) {
System.out.println("Array Value:- " + value);
if (trimmedLine.equals(value))
found=true;
}
if(!found)
fileWriter.write(trimmedLine + System.getProperty("line.separator"));
The fileWriter.write call should be outside of the "for" loop.
I want to write small java program to read data file first field and add seqcution number
Input file:
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Output file should be:
robert,190 vikign,...,0
robert,2401 windy,...,1
robert,1555 oakbrook,...,2
michell,2524 sprint,...,0
michell,1245 oakbrrok,...,1
xyz,2455 xyz drive,....,0
Check first field when value change sequction number start back to 0 otherwise add sequction number by 1
here is my code:
public static void createseq(String str) {
try {
BufferedReader br = null;
BufferedWriter bfAllBWP = null;
File folderall = new File("Sort_Data_File_Out");
File[] BFFileall = folderall.listFiles();
for (File file : BFFileall) {
br = new BufferedReader(new FileReader(file));
String bwp = "FinalDataFileOut\\" + str;
bfAllBWP = new BufferedWriter(new FileWriter(bwp));
String line;
line = br.readLine();
String[] actionID = line.split("\\|");
String fullname = actionID[0].trim();
int seq = 0;
String fullnameb;
while ((line = br.readLine()) != null) {
actionID = line.split("\\|");
fullnameb = actionID[0].trim();
if(fullname.equals(fullnameb)) {
seq++;
}
else {
System.out.println(line + "======" + seq + "\n");
seq = 0;
fullname = fullnameb;
}
System.out.println("dshgfsdj "+line + "======" + seq + "\n");
}
}
}
catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
The below code will fix the issue.I have updated the code if you face any pblm plz let me know :
Input :
robert,190 vikign,...
robert,2401 windy,...
robert,1555 oakbrook,...
michell,2524 sprint,...
michell,1245 oakbrrok,...
xyz,2455 xyz drive,....
Code :
public static void createseq() {
try {
File file = new File("d:\\words.txt"); //Hardcoded file for testing locally
BufferedReader br = new BufferedReader(new FileReader(file));
HashMap<String,Integer> counter = new HashMap<String, Integer>();
String line;
while((line = br.readLine())!= null)
{
String[] actionID = line.split(",");
String firstName = actionID[0];
if(counter.containsKey(firstName))
{
counter.put(firstName, counter.get(firstName) + 1);
}
else
{
counter.put(firstName,0);
}
System.out.println(line+" "+counter.get(firstName));
}
br.close();
} catch(Exception letterproof) {
letterproof.printStackTrace();
}
}
Ouput Come :
robert,190 vikign,... 0
robert,2401 windy,... 1
robert,1555 oakbrook,... 2
michell,2524 sprint,... 0
michell,1245 oakbrrok,... 1
xyz,2455 xyz drive,.... 0