Java csv file unable to write string like 012365479 - java

Hi write a java code to write the output into a csv file. This is the sample code:
File downloadPlace = new File(realContextPathFile, "general");
File gtwayDestRateFile = new File(downloadPlace, (new StringBuilder("ConnectionReport")).append(System.currentTimeMillis()).append(".csv").toString());
PrintWriter pw = new PrintWriter(new FileWriter(gtwayDestRateFile));
pw.print("Operator name,");
pw.print("Telephone Number,");
pw.print("Op1");
pw.print("012365479");
pw.print("Op2");
pw.print("09746");
pw.close();
p_response.setContentType("application/octet-stream");
p_response.setHeader("Content-Disposition", (new StringBuilder("attachment; filename=\"")).append(gtwayDestRateFile.getName()).append("\"").toString());
FileInputStream fis = new FileInputStream(gtwayDestRateFile);
byte buf[] = new byte[4096];
ServletOutputStream out = p_response.getOutputStream();
do
{
int n = fis.read(buf);
if(n == -1)
break;
out.write(buf, 0, n);
} while(true);
fis.close();
out.flush();
In both case the output is like this: 12365479 instead of 012365479
And 9746 instead of 09746
Can anyone tell me how can i solve this problem?

Are you sure that the file is written wrongly, and you're not just opening it in Excel which is interpreting these as numbers and thus losing the leading zeroes? Try opening it in a text editor.

If you write to System.out instead you get
Operator name,Telephone Number,Op1012365479Op209746
As you can see the 0 is where you would expect. Perhaps the problem is you don't have , between fields.
If you open such a file using excel it will remove leading 0 as it assume its a number. To avoid this you need to use double quotes around the field so it is treated as text.

Read the file in a text editor, my guess is that it has the zero and what's reading it is thinking it's a number. Try putting quotes round it.
pw.print("\"012365479\"");

Related

FileInputStream and FileOutputStream: Read and write to the same file

I created a text file with the content "Hello" and I was trying to read these characters from the file and write it back to the same file again.
Assumptions:
1. the file now has the content "Hello" (Overwritten)
2. the file now has the content "HelloHello" (Appended)
3. the file now has the content infinite "Hello" (or an exception gets thrown)
Actual result:
Original "Hello" characters gets deleted from the text file, and the file was left empty.
Actual test
#Test
public void testCopyStream() throws IOException {
File workingDir = new File(System.getProperty("user.dir"));
File testFile = new File(workingDir, "/test.txt");
FileReader fin = new FileReader(testFile);
FileWriter fos = new FileWriter(testFile);
copyStream(fin, fos);
fin.close();
fos.close();
}
I have created the following method for "copying" the data in the InputStream to the OutputStream:
private void copyStream(Reader in, Writer out) throws IOException {
int b;
while ((b = in.read()) != -1) {
out.write(b);
}
}
I tried using debugger to find out the problem, and the debugger shows b = in.read() was assigned -1 at the first iteration of the while loop. Then I executed the code step by step while inspecting the file's content and found that "Hello" keyword got deleted from the file right after statementfinal FileWriter fos = new FileWriter(testFile); gets executed.
I first thought this was due to the InputStream and OutputStream were pointed to the same file so the file gets sort of "locked" by JVM for execution safety?
So I tried swapping those two lines:
FileWriter fos = new FileWriter(testFile);
FileReader fin = new FileReader(testFile);
And the result turned out the same: the file content got eliminated right after the statement FileWriter fos = new FileWriter(testFile);
My questions is: why the content gets cleaned out by FileWriter?. Is this some behavior related to FileDescriptor? Is there a way to read and write to the same file?
Just FYI,
copyStream() method is working fine, I have tested it with other tests.
It's not about using append() method instead of write()
The statement FileWriter fos = new FileWriter(testFile); truncates the existing file.
It does not make sense for you to use streaming access to read and write the same file, as this won't give reliable results. Use RandomAccessFile if you want to read / write the same file: this has calls to seek current position and perform read or writes at different positions of a file.
https://docs.oracle.com/javase/7/docs/api/java/io/RandomAccessFile.html
FileWriter actually deletes everything in a file before writing. To preserve the text, use
new FileWriter(file, true);
The true parameter is the append parameter of the filewriter. Otherwise it will just overwrite everything

Reading stream in java with file greater than 3 GB in JAVA [duplicate]

Hey I'm trying to open a file and read just from an offset for a certain length!
I read this topic:
How to read a specific line using the specific line number from a file in Java?
in there it said that it's not to possible read a certain line without reading the lines before, but I'm wondering about bytes!
FileReader location = new FileReader(file);
BufferedReader inputFile = new BufferedReader(location);
// Read from bytes 1000 to 2000
// Something like this
inputFile.read(1000,2000);
Is it possible to read certain bytes from a known offset?
RandomAccessFile exposes a function:
seek(long pos)
Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
FileInputStream.getChannel().position(123)
This is another possibility in addition to RandomAccessFile:
File f = File.createTempFile("aaa", null);
byte[] out = new byte[]{0, 1, 2};
FileOutputStream o = new FileOutputStream(f);
o.write(out);
o.close();
FileInputStream i = new FileInputStream(f);
i.getChannel().position(1);
assert i.read() == out[1];
i.close();
f.delete();
This should be OK since the docs for FileInputStream#getChannel say that:
Changing the channel's position, either explicitly or by reading, will change this stream's file position.
I don't know how this method compares to RandomAccessFile however.

Two streams and one file

What will happen if I create two instances of class FileInputStream and FileOutputStream using the default constructor and as an argument specify the same path and file name like this..
FileInputStream is = new FileInputStream("SomePath/file.txt");
FileOutputStream os = new FileOutputStream("SamePath/file.txt");
Let's imagine that we have a few strings inside the file "file.txt". Next, using a loop I am trying to read bytes from the file.txt and write them into the same file.txt each iteration, like this:
while (is.available()>0){
int data = is.read();
os.write(data);
}
is.close();
os.close();
The problem is that when I am trying to run my code, all text from the file.txt just erasing. What happens when two or more streams trying to work with the same file? How does Java or the file system work with such a situation?
It depends on your operating system. On Windows the new FileOutputStream(...) will probably fail. On Unix-line systems you will get a new file while the old one continues to be readable.
However your copy loop is invalid. available() is not a test for end of stream, and it's not much use for other purposes either. You should use something like this:
byte[] buffer = new byte[8192];
int count;
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}

Japanese character not showing properly converting CSV file

I am converting CSV file from Tatoeba project. It contains Japanese characters. I am inserting data into SQLite database. Insertion is going without a problem, but characters are showing not properly.
If I insert directly:
String str = content_parts[2];
sentence.setValue(str);
Getting values like this:
ãã¿ã«ã¡ãã£ã¨ãããã®ããã£ã¦ãããã
I have tried to decode to UTF8 from JIS:
String str = content_parts[2];
byte[] utf8EncodedBytes = str.getBytes("JIS");
String s = new String(utf8EncodedBytes, "UTF-8");
sentence.setValue(s);
JIS:
$B!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!r!)!)!/!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)!r!)!)!)!)!)!)!)!)!)!)!)!)!)!)!)(B
Shift-JIS:
????\??????�N?�}??????????????????��?????�N?�N???��??????
Shift_JIS:
????\????????????????????????��?�N??????????????????��??????
CSV file (when opened by Excel 2010)
n きみにちょっとしたものをもってきたよ。
What I am doing wrong? How to solve this problem?
If you are still searching for solution, refer below link
setting-a-utf-8-in-java-and-csv-file and handle Japanese characters
csv-reports-not-displaying-japanese-characters
In brief, add BOM(byte order mark) characters to your file outputstream before passing it to outputstream writer.
String content="some string to write in file(in any language)";
FileOutputStream fos = new FileOutputStream("D:\csvFile.csv");
fos.write(239);
fos.write(187);
fos.write(191);
Writer w = new BufferedWriter(new OutputStreamWriter(fos, StandardCharsets.UTF_8));
w.write(content);
w.close();
Hope this will help

Broken Text : reading larger size text in android

i have a question about Broken text when android app is reading large size text file.
I am trying to build the app to read large size text file(about 10mb)
when I am reading a file and using System.println to check the contents of text file
However, when I display message but print statement
it displays broken text such as..
��T��h��e�� ��P��r��o��j��e��c��t�� ��G��u
when I was reading small size of rtf was find, but i used text file then i made problems
I used code like ..
String UTF8 = "utf8";
int BUFFER_SIZE = 8192;
File gone = new File(path);
FileInputStream inputStream = new FileInputStream(gone);
// FileInputStream inputStream = openFileInput(gone);
if ( inputStream != null ) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,UTF8);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader, BUFFER_SIZE);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
System.out.println(ret);
}
I was thinking about that it can be problem of encoding. there fore i added utf8 option.
However, it still doesn't work ..
Does anyone know solution of broken text ?
UPDATE:
I think, I solved problem.
I create new text file from window text editor and then i copy and paste content.
Now , it is reading file correctly
It may be wrong encoding for the given file, may be the file does not contain text, may be console does not support the characters.
Besides the code is too long, here's a one line solution
String s = new String(Files.readAllBytes(Paths.get(file)), "UTF-8");
The file may contain images or unsupported format, in that case it'll display like that.

Categories

Resources