out.write() in java , how to insert newline - java

When writing to a text file in java , how do I enter values into a new line
code snippet
while (rs.next()) {
int sport = rs.getInt("sport");
String name = rs.getString("name");
out.write(sport + " : " + name);}
the text file populates " value1 value2 value3...etc"
I want it to populate
value1
value2
value3
.

If 'out' is a PrintWriter, use println().
If 'out' is a BufferedWriter, use newLine().
If 'out' is some other Writer, use write('\n'), or append the newLine directly to the string you're writing. If you want the system's line separator, see System.getProperty() with the value "line.separator".

Very simple
out.write(sport + " : " + name + "\n");
That's all.

use out.write(10); to add new line. 10 is acsii character for newline. But it is not work for Indirect/Direct Buffer type FileChannel.

Related

String comparison resulting in incorrect result

I have a path URL written in a file. I use the Scanner class to record that URL and output it to string variable "s". I then use the .equals() method to compare it and the path URL in my "gameDataFile" File object. The result is false, despite them being the same string as recorded in my console. What is happening here?
Path URL in file:
src\gameData\character_data.csv
Code snippet:
String s = in.next(); // in is a java.util.Scanner object
System.out.println(gameDataFile.getPath()); // gameDataFile is a java.io.File object
System.out.println(s);
System.out.println(s.equals(gameDataFile.getPath()));
Console output:
src\gameData\character_data.csv
src\gameData\character_data.csv
false
EDIT: as per request of #MTilsted, the following code snippet
String s = in.next();
System.out.println("'" + gameDataFile.getPath() + "'");
System.out.println("'" + s + "'");
System.out.println(s.equals(gameDataFile.getPath()));
Results in the console output:
'src\gameData\character_data.csv'
'
false
It seems to have replaced the URL with one single quotation mark
Try this instead:
String s = in.next(); // in is a java.util.Scanner object
System.out.println("'" + gameDataFile.getPath() + "'"); // gameDataFile is a java.io.File object
System.out.println("'" + s + "'");
System.out.println(s.equals(gameDataFile.getPath()));
Thanks to #VGR, the problem was that the String "s" contains an addition "Carriage return" character (ascii code 13).
The utf8 file in windows has a BOM (byte order mark) at the start of the file by default. It is invisible, but it really exist. I think it cause two string different even if they look the same.
add a backslash before the single quote

useDelimeter(",") not working

I have a text file that holds data like this:
Jones,Mary,903452
4342,2.5,A
3311,4,B+
I'm using Scanner to read the file. This is my code:
while(reader.hasNextLine())
{
reader.useDelimiter(",");
String lastN = reader.next();
String firstN = reader.next();
String id = reader.nextLine();
String course1 = reader.next();
double credits = reader.nextDouble();
String grade = reader.nextLine();
}
But when I print the line on the console, the , on the last part of the line doesn't get delimited and it prints like this:
Jones, Mary, ,903452
4342, 2.5, ,A
6.5, ,3.569
My toString method on my class:
public String toString() {
return lastName + ", " + firstName + ", " + idNo + "\n"
+ courseOne + ", " + credits + ", " + grade;
I'm searched around for a solution. I tried reader.useDelimiter("[,]") and reader.useDelimiter(",|,") but still gives me the same output. How can I fix this?
From the Scanner's documentation:
This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.
(Emphasis mine) This means that the whole rest of the line is returned, including delimiters. Setting id to reader.next() wouldn't work because it sucks up everything until the next delimiter. A better solution would be to make it accept line breaks as a delimiter, like so:
reader.useDelimiter("[,\n]");

how to put data in .csv file with commas(,) in java(netbeans ide)?

I want to put my string in (.csv) file.
but if string contains commas, it split and moves to next cell.
String str=resultSet.getString();
Since you're writing a CSV file with comma delimiter and your text happens to have a comma in it as well, you need to wrap your text within double quotes:
String str = "\"hello, world\"";
So, if the string you want to write is str:
String str = ...;
...
str = "\"" + str + "\"";// do this before put str content in your csv file
This should work.
Double quote the column value if there's an embedded comma:
Ex:
column1_data, column2_data, "column3_data, new_data", column4_data
here it will consider column3_data, new_data as value in column3

writing a specific string to a file with Java

my codes dont seem to properly address what i intend to achieve.
a long string instead of a well broken and seperated string
it does not handle the 'seperator' appropriately ( produces , instead of ",")
also the 'optional' ( produces ' instead of " '")
Current result:
LOAD DATA INFILE 'max.csv'BADFILE 'max.bad'DISCARDFILE
'max.dis' APPEND INTO TABLEADDRESSfields terminated by,optionally enclosed
by'(ID,Name,sex)
the intended result should look like this
is there a better way of doing this or improving the above codes
Yeah. Use the character \n to start a new line in the file, and escape " characters as \". Also, you'll want to add a space after each variable.
content = " LOAD DATA\nINFILE "+ fileName + " BADFILE "+ badName + " DISCARDFILE " +
discardName + "\n\nAPPEND\nINTO TABLE "+ table + "\n fields terminated by \"" + separator
+ "\" optionally enclosed by '" + optional + "'\n (" + column + ")";
This is assuming fileName, badName, and discardName include the quotes around the names.
Don't reinvent the wheel... the apache commons-io library does all that in one line:
FileUtils.write(new File(controlName), content);
Here's the javadoc for FileUtils.write(File, CharSequence):
Writes a CharSequence to a file creating the file if it does not exist
To insert a new line you need to use \n or \r\n for windows
for example
discardName + "\n" //New line here
"APPEND INTO TABLE"
For the double quote symbol on the other hand you need to specifically type \" around the comma:
"fields terminated by \"" + separator +"\""
which will produce this ","
and that is similar to what the optional variable needs to be

\n won't work, not going to a new line

I'm creating a small program that saves a int value into a text file, saves it, and loads it when you start the program again. Now, I need 3 more booleans to be stored in the text file, I am writing things in the file with
public Formatter x;
x.format("%s", "" + m.getPoints() + "\n");
Whenever I want to go to a new line in my text file, with \n, it wont go to a new line, it will just write it directly behind the int value. I tried doing both
x.format("%s", "" + m.getPoints() + "\n");
x.format("%s", "" + m.getStoreItem1Bought() + "\n");
and
x.format("%s%s", "" + m.getPoints() + "\n", "" + m.getBought() + "\n");
but, both will just write the boolean directly behind the int value, without starting a new line. Any help on this?
I am using Windows 7 Ultimate 64 bits, and my text editor is Eclipse, I am running all of the code with Eclipse too.
More specifically, I would recommend using:
x.format("%d%n%s%n", m.getPoints(), m.getStoreItem1Bought());
Use this instead:
public static String newline = System.getProperty("line.separator");
Both of this options work. Your problem is in how you format the output:
System.out.format("%s" + newline + "%s" + newline, "test1", "test2");
System.out.format("%s%n%s", "test1", "test2");
Output:
test1
test2
test1
test2
Try using %n instead of \n when using format. For details on this, please see the Formatter API and search this page for "line separator" and you'll see.
No problem here:
System.out.format ("first: %s%s", "" + x + "\n", "" + y + "\n");
While I would prefere, to integrate the \n into the format String, not the values:
System.out.format ("second: %s\n%s\n", x, y);
Using Formatter.format works the same.
Well your syntax is surely quite.. interesting. Why use the formatting method if you're just piece the string together anyways? Also since you nowhere say what stream you're using we have to guess a bit, but anyways.
Anyways I'm betting that 1. you're using windows and 2. that the editor (I bet on notepad) you're using only reacts to \r\n since that's the correct newline for Windows. To fix this DON'T hardcode \r\n in your code but instead use %n and use the printf function correctly (ie don't piece the string together!).
Otherwise if you really have to piece the string together:
String newline = System.getProperty("line.separator");
x.format("%s", "" + m.getPoints() + newline);
will work.

Categories

Resources