Simple Line replace not working in Java - java

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.

Related

Java read specific parts of a CSV

I created the following code to read a CSV-file:
public void read(String csvFile) {
try {
File file = new File(csvFile);
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String line = "";
String[] tempArr;
while((line = br.readLine()) != null) {
tempArr = line.split(ABSTAND);
anzahl++;
for(String tempStr : tempArr) {
System.out.print(tempStr + " ");
}
System.out.println();
}
br.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
I have a CSV with more than 300'000 lines that look like that:
{9149F314-862B-4DBC-B291-05A083658D69};Gebaeude;TLM_GEBAEUDE;;Schiessstand;{41C949A2-9F7B-41EE-93FD-631B76F2176D};Altdorf 300m;offiziell;Hochdeutsch inkl. Lokalsprachen;Einfacher Name;;684600;295930;400
How can I now only get the some parts out of that? I only need the bold/italic parts to work with.
Without further specifying what your requirements/input limitations are the following should work within your loop.
String str = "{9149F314-862B-4DBC-B291-05A083658D69};Gebaeude;TLM_GEBAEUDE;;Schiessstand;{41C949A2-9F7B-41EE-93FD-631B76F2176D};Altdorf 300m;offiziell;Hochdeutsch inkl. Lokalsprachen;Einfacher Name;;684600;295930;400";
String[] arr = str.split("[; ]", -1);
int cnt=0;
// for (String a : arr)
// System.out.println(cnt++ + ": " + a);
System.out.println(arr[6] + ", " + arr[15] + ", " + arr[16]);
Note that this assumes your delimiters are either a semicolon or a space and that the fields desired are in the fix positions (6, 15, 16).
Result:
Altdorf, 684600, 295930

PrintWriter writes blank file

I want to change the score of the user, but instead of overwriting the file with new scores, it just makes an empty file.
The lines are written like this: "username-password-wins-losses-ties"
try {
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
PrintWriter pw = new PrintWriter(new FileWriter("users.txt"));
String[] tab = null;
String zlepek = "";
while(br.readLine()!=null) {
String line = br.readLine();
tab = line.split("-");
int countLoss = Integer.parseInt(tab[3]+plusLoss);
int countWin = Integer.parseInt(tab[2]+plusWin);
int countTie = Integer.parseInt(tab[4]+plusTie);
if(tab[0].equals(loginUser.user)) {
String newScore = (tab[0] + "-" + tab[1] + "-" + countWin + "-" + countLoss + "-" + countTie + "\n");
zlepek = zlepek+newScore;
} else {
String oldScore = (tab[0] + "-" + tab[1] + "-" + tab[2] + "-" + tab[3] + "-" + tab[4] + "\n");
zlepek = zlepek+oldScore;
}
}
pw.print(zlepek);
pw.close();
br.close();
plusWin = 0;
plusLoss = 0;
plusTie = 0;
} catch(IOException e) {}
Any help is appreciated.
You are skipping the first line and every odd lines, change the code like below
String line = null;
while ((line = br.readLine()) != null){
// code
}
also you are reading and writing on a same file, you can't read and write simultaneously on a same file. If you want you can write it to a temporary file and rename it later.
If you want write on the same file, you have to close the reader before writing, see below
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
String line = null;
StringBuilder sb = new StringBuilder();
String zlepek = "";
while ((line = br.readLine()) != null) {
zlepek = // logic to get value
sb.append(zlepek).append("\n");
}
br.close();
PrintWriter pw = new PrintWriter(new FileWriter("users.txt")); // pass true to append
pw.print(sb);
pw.close();
The problem is with this line while(br.readLine()!=null), you read the line but didnt save it, so it doesnt know where it is and the line will always be empty after you read the line and dont save it.
try to remove this String line = br.readLine(); and read it in the while. define the String line; and while( (line = br.readLine()) != null){ // do something}
try {
String[] tab = null;
String line = null;
tab = line.split("-");
int countLoss = Integer.parseInt(tab[3]+plusLoss);
int countWin = Integer.parseInt(tab[2]+plusWin);
int countTie = Integer.parseInt(tab[4]+plusTie);
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
StringBuilder sb = new StringBuilder();
String zlepek = "";
while ((line = br.readLine()) != null) {
if(tab[0].equals(loginUser.user)) {
String newScore = (tab[0] + "-" + tab[1] + "-" + countWin + "-" + countLoss + "-" + countTie + "\n");
zlepek = zlepek+newScore;
} else {
String oldScore = (tab[0] + "-" + tab[1] + "-" + tab[2] + "-" + tab[3] + "-" + tab[4] + "\n");
zlepek = zlepek+oldScore;
}
sb.append(zlepek).append("\n");
}
br.close();
PrintWriter pw = new PrintWriter(new FileWriter("users.txt")); // pass true to append
pw.print(sb);
pw.close();
plusWin = 0;
plusLoss = 0;
plusTie = 0;
} catch(IOException e) {}
}

replace a line to above line for every two lines java

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);
}

Removing Array Items from file

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.

Java Code check fields in duplicate, when value change start again

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

Categories

Resources