Java Writing in a File [duplicate] - java

This question already has answers here:
How to remove line breaks from a file in Java?
(17 answers)
Closed 9 years ago.
I am writing in a file and I want it to output into a csv file this way:
Group Members
1 Name1
Name2
Name3
code:
FileWriter fw = new FileWriter(csv);
BufferedWriter pw = new BufferedWriter(fw);
pw.write("Group,");
pw.write("Members");
pw.newline();
String mem=some_method();
pw.write("1,");
pw.write(mem);
pw.newLine();
My String mem has '\n' every after the names and so when it writes in the file, '\n' is read then writes into the next line. How can i achieve the above output without modifying the some_method()?

You want to strip the new line characters in mem.
Check out
Remove end of line characters from Java string
Put simply you can add the line mem = mem.replaceAll("(\\r|\\n)", "");

Try as below,
String mem=some_method();
mem = mem.replace("\n", "");
Instead of \n you can also use System.getProperty("line.separator") which gives you platform independent line separator.
mem = mem.replace(System.getProperty("line.separator"), "");

Why dont you combine the Group and Member together in one write method like:
pw.write("Group \t\t Members");
and do the same with the other contents. Hope this helps.

Related

add data to file specific line in Java [duplicate]

I would like to know if it's possible to add a line in a File with Java.
For example myFile :
1: line 1
2: line 2
3: line 3
4: line 4
I would like to add a line fox example in the third line so it would look like this
1: line 1
2: line 2
3: new line
4: line 3
5: line 4
I found out how to add text in an empty file or at the end of the file but i don't know how to do it in the middle of the text without erasing the line.
Is the another way than to cut the first file in 2 parts and then create a file add the first part the new line then the second part because that feels a bit extreme ?
Thank you
In Java 7+ you can use the Files and Path class as following:
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
To give an example:
Path path = Paths.get("C:\\Users\\foo\\Downloads\\test.txt");
List<String> lines = Files.readAllLines(path, StandardCharsets.UTF_8);
int position = lines.size() / 2;
String extraLine = "This is an extraline";
lines.add(position, extraLine);
Files.write(path, lines, StandardCharsets.UTF_8);
You may read your file into an ArrayList, you can add elements in any position and manipulate all elements and its data, then you can write it again into file.
PD: you can not add a line directly to the file, you just can read and write/append data to it, you must manipulte de data in memory and then write it again.
let me know if this is useful for you

Can't print newline character (\n) in strings returned by String.split in Java

I am writing a Java program in which a tab separated values (TSV) file containing two columns of information is read by a BufferedReader and then split into two components (which will serve as [key,value] pairs in a HashMap later in the program) using String.split("\t"). Let's say the first line of the TSV file is as follows:
Key1\tHello world\nProgramming is cool\nGoodbye
The code shown below would separate this line into "Key1" and "Hello world\nProgramming is cool\nGoodbye":
File file = new File("sample.tsv");
BufferedReader br = new BufferedReader(new FileReader(file));
String s = br.readLine();
String[] tokens = new String[2];
tokens = s.split("\t");
The problem now comes in trying to print the second string (i.e. tokens[1]).
System.out.println(tokens[1]);
The line of code above results in the second string being printed with the newline characters (\n) being ignored. In other words, this is printed...
Hello world\nProgramming is cool\nGoodbye
...instead of this...
Hello worldProgramming is coolGoodbye
If I create a new string with the same text as above and use the String.equals() method to compare the two, it returns false.
String str = "Hello world\nProgramming is cool\nGoodbye";
boolean sameString = str.equals(tokens[1]); // false
Why can't special characters in the strings returned by String.split() be printed properly?
BufferedReader.readLine() read your string as one line, as that's how it's represented in the file. Buffered reader didn't read "\n" as ASCII(10) 0x0A, it read "ASCII(92) 0x9C ASCII(110) 0x6E".
If you type the input file the way you expect to see it with your text editor, it will print the way you expect.
on a unix like system:
echo -e "Hello world\nProgramming is cool\nGoodbye" > InputFile.result_you_want
echo "Hello world\nProgramming is cool\nGoodbye" > InputFile.result_you_get
You could use a program like echo to convert your TSV, but then you will need to split on the "\t" character, ASCII(9) 0x09, and not a literal "\t".
Split takes a regular expression. Escaping that tab character may be interesting.
"\t" or "\\t" may do the trick there.
If this is for work, you may want to use a tool or library to work around having to convert your file with echo.
String parsing in Java with delimeter tab "\t" using split has some suggestions there.
Searching for CSV java API's could be very useful. Most will let you set the delimiter character and information on line ending formats.
because in computer aspect, the text '\n' is not like the binary '\n'.
the first line of ur file, i think is like key1 Hello world\nProgramming\ncool
so it's the it can split the \t,but when it comes to print, it only show the text
'\n' but not the binary '\n' which will make the new Line

How to replace String with different slashes? [duplicate]

This question already has answers here:
java split function
(6 answers)
Closed 7 years ago.
I need to rename some paths in database.
I rename folder:
String mainFolder= "D:\test\1\data"; //folder renamed from fd
Then i need to rename all files and directories inside that folder:
String file1="D:\test\1\fd\dr.jpg";
String folder1="D:\test\1\fd\fd"; // in this case last fd needs to be renamed
String folder2="src/fd/fd/"; //fake path also needs to be renamed
What is the best and fastest way to rename that strings?
My thoughts about "/":
String folder2= "src/da/da";
String[] splittedFakePath = folder2.split("/");
splittedFakePath[splittedFakePath.length - 2] = "data";
StringBuffer newFakePath = new StringBuffer();
for (String str : splittedFakePath) {
newFakePath.append(str).append("/");
}
String after rename: src/data/da/
But when im trying split by "\":
Arrays.toString(Pattern.compile(File.separator).split(folder1));
I receive:
java.util.regex.PatternSyntaxException: Unexpected internal error near index 1
\
^
Look into java's String replace(...) method.
It is wonderful for string replacement, much better than attempting a regex.
Keep in mind that real directory handling has a few special cases, which don't lend themselves well to direct string manipulation. For example '//' often gets compacted to '/' in Unix like systems, and if you care about proper directory corner-cases, then use the Java Path class

Parsing a string using regex [duplicate]

This question already has answers here:
How do I get the file name from a String containing the Absolute file path?
(13 answers)
Closed 7 years ago.
I'm trying to slpit the string /home/user/test.dat
I use String[] split = file.split("(?!.*/)"); but split[1] only returns the first character instead of the whole file name. How would I edit my regex so that it returns everything past the last forward slash?
Unless there's some compelling reason to use a regular expression, I would use the simple String.lastIndexOf(int). Something like,
String file = "/a/b/c/d/e/test.dat";
int afterSlash = file.lastIndexOf('/');
if (afterSlash > -1) {
file = file.substring(afterSlash + 1);
}
System.out.println(file);
Output of above being (the requested)
test.dat
Regex
\/((\w+)\.(\w+))$
Debuggex Demo
However, since you are using Java simply load the string into the File helper which can pull out the filename:
Java
Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

How can i split this string in Java? [duplicate]

This question already has answers here:
Java: splitting a comma-separated string but ignoring commas in quotes
(12 answers)
Closed 9 years ago.
I have a problem with splitting a sentence in Java
input string :
"retinol,\"3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid\",C034534,81485-25-8,\"Carcinoma, Hepatocellular\",MESH:D006528,Cancer|Digestive system disease,,17270033,therapeutic";
and i want to split it and get splitted terms like as follows ;
retinol
3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid
C034534
81485-25-8
Carcinoma, Hepatocellular
MESH:D006528
Cancer|Digestive system disease
(nothing)
17270033
therapeutic
I tried few way to solve this problem such as Pattern/Matcher and split(",")[] etc..
But, i couldn't find the answer..
As discussed in the comments, since you're parsing a CSV file, you're going to want to use a library specifically written to parse CSVs. Otherwise you'll continue to run into problems where what you write is "useless when a different patten comes out" (as you said).
However, to solve the question at hand you just have to split on a comma, ignoring commas inside of quotes. So you can do this (from this answer):
String input = "retinol,\"3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid\",C034534,81485-25-8,\"Carcinoma, Hepatocellular\",MESH:D006528,Cancer|Digestive system disease,,17270033,therapeutic";
String[] output = input.split(",(?=([^\"]*\"[^\"]*\")*[^\"]*$)");
for(String s : output){
System.out.println(s);
}
This will give you this output (note the quotes and empty line):
retinol
"3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid"
C034534
81485-25-8
"Carcinoma, Hepatocellular"
MESH:D006528
Cancer|Digestive system disease
17270033
therapeutic
You can replace the quotes and ignore the empty line as you wish. This loop will print the exact output requested in the question:
int i=1;
for(String s : output){
if(!s.isEmpty()){
System.out.println(i++ + ". " + s.replace("\"", ""));
}
}
Output:
retinol
3,7,11,15-tetramethyl-2,4,6,10,14-hexadecapentaenoic acid
C034534
81485-25-8
Carcinoma, Hepatocellular
MESH:D006528
Cancer|Digestive system disease
17270033
therapeutic
But, please, use a library like OpenCSV.

Categories