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);
}
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));
}
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);
}
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've the below content in a text file named Sample.txt
This is line1
This is line2
and here I want to replace this new line with and, I mean the output should be like
This is line1 and This is line2
and my code is as below.
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("C:\\Users\\home\\Desktop\\Test\\Sample.txt"));
int i = 0;
while ((sCurrentLine = br.readLine()) != null) {
String sCurrentLine1 = sCurrentLine.replaceAll("\\n+", "0NL0");
System.out.println("Line No." + i + " " + sCurrentLine1);
i++;
}
When I'm printing this, I get the output as
Line No.0 This is line1
Line No.1 This is line2
please let me know how can I replace this new line.
Thanks
You do not need to do a replaceAll The BufferedReader::readLine() method removes the \n character from the returned string in sCurrentLine. So all you have to do is append the returned lines.
Example:
try {
String sCurrentLine;
StringBuilder sb = new StringBuilder();// Declare a string builder object.
br = new BufferedReader(new FileReader("C:\\Users\\home\\Desktop\\Test\\Sample.txt"));
int i = 0;
while ((sCurrentLine = br.readLine()) != null) {
if(i>0) {
sb.append(" and ");
}
sb.append(sCurrentLine);
System.out.println("Line No." + i + " " + sCurrentLine);
i++;
}
System.out.println("Appended output " + sb.toString());
Try this,
String str = "";
while ((sCurrentLine = br.readLine()) != null) {
String sCurrentLine1 = sCurrentLine.replaceAll("\\n+", "0NL0");
str = str + sCurrentLine1 + " and ";
}
System.out.println(str.substring(0,(str.length()-5)));
Hope it helps you.
I have files containing text in pattern like this
Type:status
Origin:some text
Text:some text
URL:some url
Time:time
around 500 lines with same pattern. I want to extract only the text part from it. I tried reading the file with BufferedReader and used indexOf("Text") and indexOf("URL") and subString(i,j) but its giving exception at run time. How can I do this. My code:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
str= str + s;
i = str.indexOf("Text:");
j= str.indexOf("URL:");
String a= str.substring(i, j);
bw.write(a);
}
br.close();
bw.close();
The "Text:" is found first in the 3rd line and "URL:" in the 4th, but if your program doesn't find both strings, it throws an exception.
Even if it worked you would find the same text over and over again.
Try something like this:
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter wr = new FileWriter("new.txt");
String s;
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
if (s.startsWith("Text:"))
bw.write(s);
}
br.close();
bw.close();
You could use
String[] pieces = str.split(":");
That will give you an array of strings split by what ever you put in the parenthesis. Then if you know the pattern you can get each piece out by iterating through it in a loop. For example: if you know that Type is at [0] and six things in each sequence you can say that the next Type will be at [6] and so on.
You should check for indexes. Of i and j. If one line is wrong, it will skip it and print the line that is wrong to the console. You should probably handle it in a different way but keep in mind that substring shouldn't love indexes of -1.
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String tokenText = "Text:";
String tokenURL = "URL:";
FileWriter wr = new FileWriter("new.txt");
// char buffer[] = null;
String s;
String str="";
BufferedWriter bw = new BufferedWriter(wr);
while ((s = br.readLine()) != null) {
String a;
str = str + s;
i = str.indexOf(tokenText);
j = str.indexOf(tokenURL);
if (i < 0 && j >= 0){
// pad with the token string
a = s.substring(j + tokenURL.length);
} else if(i >= 0) {
// pad with the token string
a = s.substring(i + tokenText.length);
} else {
System.out.printl("Unparsed line:");
System.out.printl(s);
}
bw.write(a);
}
br.close();
bw.close();
That said, as jonhchen902 said in the comments, you could also check for the strings after the while loop. It really depends on your input file and if you're expecting to find the "string" multiple times or once.
According to your example, Text: and Url: are on consecutive lines.
Your problem is you're reading the file line by line (br.readLine()), so calling indexOf() will most of the time return -1 in i or j (and you will never find both strings, since they aren't on the same line).
As the javadoc of substring() states, calling the method with a negative start index will throw an IndexOutOfBoundsException. So your approach isn't right.
You should instead parse the file line by line as you're doing, and simply test for a positive index to the call to indexOf("Text:"), and then substring the current line starting at the returned index + 5.
Not tested:
while ((line = br.readLine()) != null) {
i = line.indexOf("Text:");
if (i > 0) {
String text = line.substring(i);
bw.write(text + "\n");
}
}