Unexpected line break using PrintWriter - java

I don't know why PrintWriter break the line when it see this symbol '##'
I want to write these line to .txt file
But got this, you can see it got some unexpected rows:
Part of my code:
try(OutputStreamWriter fw = new OutputStreamWriter(
new FileOutputStream(filePath + "\\" +file_number + "_"+ info.getFileName(), true),
StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw, false)) {
JCoTable rows = function6.getTableParameterList().getTable("DATA");
for (int i = 0; i < rows.getNumRows(); i++) {
rows.setRow(i);
out.write(Integer.toString(CURRENT_ROW) + ((char)Integer.parseInt(info.getFileDelimited()))+ rows.getString("WA") + "\n");}

The ABAP table contains 6 rows and your output contains 6 rows. So I guess you mean with "additional rows" the 2 additional line breaks in rows no. 2 and 6.
I assume this is because these line breaks are part of the text in these rows. The SAP GUI doesn't write these control characters and outputs them as '##', but the Java code prints these characters, of course. I guess these 2 substituted chars '##' actually are the control characters END OF LINE (U+000A) and CARRIAGE RETURN (U+000D).
You can check their real character codes with the ABAP debugger's hexadecimal view or in your Java development environment debugger.

Related

BufferedReader - Output columns in in different order JAVA

I have 2 csv files with column 'car', 'bike', 'tractor' etc
The below code prints out data from the csv which works fine, however cvs 1 prints out in a different or to csv 2 so I want to arrange the columns in a different order.
From this code, how can I organise the data to print out in order of which column I want first, second etc.
BufferedReader r = new BufferedReader(new InputStreamReader(str));
Stream lines = r.lines().skip(1);
lines.forEachOrdered(
line -> {
line= ((String) line).replace("\"", "");
ret.add((String) line);
The columns print out like this:
csv 1
Car, Bike, Tractor, Plane, Train
csv 2
Bike, Plane, Tractor, Train, Car,
but I want to manipulate the code so the two csv files print out in the same order like;
Bike, Plane ,Tractor, Train, Car
I can't use the likes of col[1],col[3], as the two files are in different or so I would need to call them by column name in the csv file so col["Truck"] etc
Or is there another way. Like creating a new list from the csv 1 output and rearranging ?
I haven't used BufferedReader much so I'm not sure if this is a silly question and there's a simple solution
A BufferedReader reads lines, and does not care for the content of those lines. So this code will simply save lines into ret as it is reading them:
List<String> ret = new ArrayList<>();
try (BufferedReader r = new BufferedReader(new InputStreamReader(str))) {
r.lines().skip(1).forEachOrdered(l -> ret.add(l.replace("\"", ""));
}
// now ret contains one string per CSV line, excluding the 1st
(This is somewhat better than your code in that it is guaranteed to close the reader correctly, and does not require any casts to string).
If your CSV lines do not contain any , characters that are not separators, you can modify the above code to split lines into columns; which you can then reorder:
List<String[]> ret = new ArrayList<>(); // list of string arrays
try (BufferedReader r = new BufferedReader(new InputStreamReader(str))) {
r.lines().skip(1).forEachOrdered(l ->
ret.add(l.replace("\"", "").split(",")); // splits by ','
}
// now ret contains a String[] per CSV line, skipping the 1st;
// with ret.get(0)[1] being the 2nd column of the 1st non-skipped line
// this will output all lines, reversing the order of columns 1 and 2:
for (String[] line : ret) {
System.out.print(line[1] + ", " + line[0]);
for (int i=2; i<line.length; i++) System.out.print(", " + line[i]);
System.out.println();
}
If your CSV lines can contain ,s that are not delimiters, you will need to learn how to correctly parse (=read) CSVs, and that requires significantly more than a BufferedReader. I would recommend using an external library to handle this correctly (for there are many types of CSVs in the wild). In particular, using Apache Commons CSV, things are relatively straightforward:
try (Reader in = new FileReader("path/to/file.csv")) {
Iterable<CSVRecord> records = CSVFormat.RFC4180.parse(in);
for (CSVRecord record : records) {
String columnOne = record.get(0);
String columnTwo = record.get(1);
}
}

Parse a semicolon separated file in Java

I have a excel file and the contents are shown below.
First line is header, second line on wards is the data.
Cell A1 contains line below (Header)
**IsShooting; Velocity; Location_x; Location_y; Location_z; Onslaught_ONSAV ; ***Event***; EventParams...**
Cell A2 contains below
0;0;0;0;0;0;0;0;0;0;0.000;0.000;0;0.000;0.000;None;0;0;0.000;-1983.610;-
Cell A3 Contains below
;0.250;0.000;0.000;0.000;0.000;***BOT_KILLED***;CTF-Geothermal.GBxBot10;XWeapons.DamTypeFlakChunk
Cell A4 Contains below
4.110;161.900;0.000;0.000;0.000;0.000;0.000;0.000;0.000;0.000;0.000;0.000;0.000;0.000;0.000;4.320;0.000;0.260;0.000;0.000;***FLAG_PICKEDUP***;0;CTF-Geothermal.GBxBot10
I want to know if there are any open Source CSV Parsers, I can use so that, I can get the data from the excel.
The above excel file contains 400 lines of data. All I want from this is the COUNT of FLAG_PICKEDUP & BOT_KILLED.
Thanks!
This is the easiest way I can think of. Use a BufferedReader to read each line. For each line split it into a String array, then check each String to see if it equals the constants that define flag pickups or bot kills.
I think Apache makes csv parser, but I've never used it. For something this simple it might just be easier to code it yourself. This is what I came up with in about 5 mins.
NOTE: All due respect, stackoverflow generally asks that you attempt to solve the problem yourself first. Since you didn't post code, we can't help you debug and we don't know if you tried to solve the problem yourself. This was simple, so I helped but you may find it easier to get support if you post your (failed) solution first.
public static void main(String[] args) throws Exception
{
int botKilledCount = 0, flagPickedUpCount = 0;
String line, botLiteral = "***BOT_KILLED***", flagLiteral = "***FLAG_PICKEDUP***";
BufferedReader reader = new BufferedReader(new FileReader(new File("!!YOUR FILE HERE!!")));
while ((line = reader.readLine()) != null)
for (String s : line.split(";"))
if (s.equals(botLiteral))
botKilledCount++;
else if (s.equals(flagLiteral))
flagPickedUpCount++;
System.out.println("Bot Killed Count: " + botKilledCount + ", Flag Pickup Count: " + flagPickedUpCount);
}
This was the output:
Bot Killed Count: 1, Flag Pickup Count: 1

Unexpected result when writing a Unicode(UTF-8) text to file

I have problem when writing a Unicode(UTF-8) text to file with java.
I want writ some text in other language (Persian) to file in java, but i receive Unexpected result after run my app.
File file = new File(outputFileName);
FileOutputStream f = new FileOutputStream(outputFileName);
String encoding = "UTF-8";
OutputStreamWriter osw = new OutputStreamWriter(f,encoding);
BufferedWriter bw = new BufferedWriter(osw);
StringBuilder row = new StringBuilder();
row.append("Some text in English language");
// in below code it should be 4 space before علی
row.append(" علی");
// in below code it should be 6 space before علی یاری
row.append(" علی یاری");
bw.write(row.toString());
bw.flush(); bw.close();
how can i solve this problem?
The output is what is expected according to the Unicode bidirectional algorithm. The entire Persian text is rendered right-to-left. If you want the individual words to be laid out left-to-right, then you need to insert a strongly left-to-right character between the two Persian words. There's a special character for this: LEFT TO RIGHT MARK (U+200e). This modification to your code should produce the correct output:
row.append("Some text in English language");
row.append(" علی");
row.append('\u200e');
row.append(" علی یاری");

How to append existing line in text file

How do i append an existing line in a text file? What if the line to be edited is in the middle of the file? Please kindly offer a suggestion, given the following code.
Have went through & tried the following:
How to add a new line of text to an existing file in Java?
How to append existing line within a java text file
My code:
filePath = new File("").getAbsolutePath();
BufferedReader reader = new BufferedReader(new FileReader(filePath + "/src/DBTextFiles/Customer.txt"));
try
{
String line = null;
while ((line = reader.readLine()) != null)
{
if (!(line.startsWith("*")))
{
//System.out.println(line);
//check if target customer exists, via 2 fields - customer name, contact number
if ((line.equals(customername)) && (reader.readLine().equals(String.valueOf(customermobilenumber))))
{
System.out.println ("\nWelcome (Existing User) " + line + "!");
//w target customer, alter total number of bookings # 5th line of 'Customer.txt', by reading lines sequentially
reader.readLine();
reader.readLine();
int total_no_of_bookings = Integer.valueOf(reader.readLine());
System.out.println (total_no_of_bookings);
reader.close();
valid = true;
//append total number of bookings (5th line) of target customer # 'Customer.txt'
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(filePath + "/src/DBTextFiles/Customer.txt")));
writer.write(total_no_of_bookings + 1);
//writer.write("\n");
writer.close();
}
catch (IOException ex)
{
ex.printStackTrace();
}
//finally
// {
//writer.close();
//}
}
}
}
To be able to append content to an existing file you need to open it in append mode. For example using FileWriter(String fileName, boolean append) and passing true as second parameter.
If the line is in the middle then you need to read the entire file into memory and then write it back when all editing was done.
This might be workable for small files but if your files are too big, then I would suggest to write the actual content and the edited content into a temp file, when done delete the old one an rename the temp file to be the same name as the old one.
The reader.readLine() method increments a line each time it is called. I am not sure if this is intended in your program, but you may want to store the reader.readline() as a String so it is only called once.
To append a line in the middle of the text file I believe you will have to re-write the text file up to the point at which you wish to append the line, then proceed to write the rest of the file. This could possibly be achieved by storing the whole file in a String array, then writing up to a certain point.
Example of writing:
BufferedWriter writer = new BufferedWriter(new FileWriter(new File(path)));
writer.write(someStuff);
writer.write("\n");
writer.close();
You should probably be following the advice in the answer to the second link you posted. You can access the middle of a file using a random access file, but if you start appending at an arbitrary position in the middle of a file without recording what's there when you start writing, you'll be overwriting its current contents, as noted in this answer. Your best bet, unless the files in question are intractably large, is to assemble a new file using the existing file and your new data, as others have previously suggested.
AFAIK you cannot do that. I mean, appending a line is possible but not inserting in the middle. That has nothing to do with java or another language...a file is a sequence of written bytes...if you insert something in an arbitrary point that sequence is no longer valid and needs to be re-written.
So basically you have to create a function to do that read-insert-slice-rewrite

Why is Java BufferedReader() not reading Arabic and Chinese characters correctly?

I'm trying to read a file which contain English & Arabic characters on each line and another file which contains English & Chinese characters on each line. However the characters of the Arabic and Chinese fail to show correctly - they just appear as question marks. Any idea how I can solve this problem?
Here is the code I use for reading:
try {
String sCurrentLine;
BufferedReader br = new BufferedReader(new FileReader(directionOfTargetFile));
int counter = 0;
while ((sCurrentLine = br.readLine()) != null) {
String lineFixedHolder = converter.fixParsedParagraph(sCurrentLine);
System.out.println("The line number "+ counter
+ " contain : " + sCurrentLine);
counter++;
}
}
Edition 01
After reading the line and getting the Arabic and Chinese word I use a function to translate them by simply searching for Given Arabic Text in an ArrayList (which contain all expected words) (using indexOf(); method). Then when the word's index is found it's used to call the English word which has the same index in another Arraylist. However this search always returns false because it fails when searching the question marks instead of the Arabic and Chinese characters. So my System.out.println print shows me nulls, one for each failure to translate.
*I'm using Netbeans 6.8 Mac version IDE
Edition 02
Here is the code which search for translation:
int testColor = dbColorArb.indexOf(wordToTranslate);
int testBrand = -1;
if ( testColor != -1 ) {
String result = (String)dbColorEng.get(testColor);
return result;
} else {
testBrand = dbBrandArb.indexOf(wordToTranslate);
}
//System.out.println ("The testBrand is : " + testBrand);
if ( testBrand != -1 ) {
String result = (String)dbBrandEng.get(testBrand);
return result;
} else {
//System.out.println ("The first null");
return null;
}
I'm actually searching 2 Arraylists which might contain the the desired word to translate. If it fails to find them in both ArrayLists, then null is returned.
Edition 03
When I debug I found that lines being read are stored in my String variable as the following:
"3;0000000000;0000001001;1996-06-22;;2010-01-27;����;;01989;������;"
Edition 03
The file I'm reading has been given to me after it has been modified by another program (which I know nothing about beside it's made in VB) the program made the Arabic letters that are not appearing correctly to appear. When I checked the encoding of the file on Notepad++ it showed that it's ANSI. however when I convert it to UTF8 (which replaced the Arabic letter with other English one) and then convert it back to ANSI the Arabic become question marks!
FileReader javadoc:
Convenience class for reading character files. The constructors of this class assume that the default character encoding and the default byte-buffer size are appropriate. To specify these values yourself, construct an InputStreamReader on a FileInputStream.
So:
Reader reader = new InputStreamReader(new FileInputStream(fileName), "utf-8");
BufferedReader br = new BufferedReader(reader);
If this still doesn't work, then perhaps your console is not set to properly display UTF-8 characters. Configuration depends on the IDE used and is rather simple.
Update : In the above code replace utf-8 with cp1256. This works fine for me (WinXP, JDK6)
But I'd recommend that you insist on the file being generated using UTF-8. Because cp1256 won't work for Chinese and you'll have similar problems again.
IT is most likely Reading the information in correctly, however your output stream is probably not UTF-8, and so any character that cannot be shown in your output character set is being replaced with the '?'.
You can confirm this by getting each character out and printing the character ordinal.
public void writeTiFile(String fileName,String str){
try {
FileOutputStream out = new FileOutputStream(fileName);
out.write(str.getBytes("windows-1256"));
} catch (Exception ex) {
ex.printStackTrace();
}
}

Categories