How to write data to the next sheet while generating CSV in Java?
response.setContentType("text/csv");
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-disposition",
"inline; filename=\"mGovData.csv\"");
OutputStream outputStream = response.getOutputStream();
byte[] bom = new byte[] { (byte) 0xEF, (byte) 0xBB, (byte) 0xBF };
outputStream.write(bom); // adds BOM
Writer out = new BufferedWriter(new OutputStreamWriter(
outputStream, "UTF-8"));
if (otmstatus != null
|| (StringUtils.isNotBlank(otmfrmDate) && StringUtils
.isNotBlank(otmtoDate))
|| (otmdaystate != null && from != null && to != null)) {
// Write the content
if (otmfrmDate != null && otmtoDate != null) {
from = new SimpleDateFormat("dd-MM-yyyy").parse(otmfrmDate);
// to = new SimpleDateFormat("dd-MM-yyyy").parse(otmtoDate);
DateFormat d = new SimpleDateFormat("dd-MM-yyyy");
to = d.parse(otmtoDate);
to.setHours(23);
to.setMinutes(59);
to.setSeconds(59);
}
otmConfigDtos = otmManager.getOtmDetailsForReport(otmstatus,
from, to, sp_Id, otmdaystate, otmphoneNo, msgText);
String csvTitles = getText("lbl.report.generate.pdf.text.otm")
+ "," + "\n"
+ getText("lbl.report.generate.pdf.text.documentdate")
+ new Date().toString() + "," + "\n"
+ getText("lbl.report.generate.pdf.text.reportdate")
+ " "
+ getText("lbl.report.generate.pdf.text.dateform")
+ " " + DateFormatUtils.format(from, "dd/MM/yyyy")
+ " " + getText("lbl.report.generate.pdf.text.dateto")
+ " " + DateFormatUtils.format(to, "dd/MM/yyyy") + "\n";
out.write(csvTitles);
out.flush();
out.close();
outputStream.close();
}
I want to know if the data written on the CSV is too bulky. Then how can we move it to the next sheet?
You can create next csv file if in firstone certain number of rows completed. And in second csv if certain rows completed, then you can write next csv file.
But in my suggestion is , write that data to a database, then everything will be very simple. Data insert, retrieval, edit etc etc will be very simple
Related
I'm trying to restore some datafiles (mostly pdfs) from a SQL Server base.
The table column is of the following type: D_BLOB(image) and contains this type of data:
As for the code and different approaches I tried, here my different parts of code combined
byte[] output = qResult.getBytes("DOCUMENT");
Blob blob = qResult.getBlob("DOCUMENT");
String document2 = qResult.getString("DOCUMENT");
InputStream input = qResult.getBinaryStream("DOCUMENT");
FileOutputStream output2 = new FileOutputStream(new File(repertoireDst + "\\" + intitule + "_test2_." + extension));
byte[] buffer = new byte[1024];
while (input.read(buffer) > 0) {
output2.write(buffer);
}
output2.close();
/************************************
* Simple input output Stream
*******************/
InputStream inputStream = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(repertoireDst + "\\" + intitule + "_test_." + extension);
int bytesRead = -1;
byte[] buffer2 = new byte[1024];
while ((bytesRead = inputStream.read(buffer2)) != -1) {
outputStream.write(buffer2, 0, bytesRead);
}
inputStream.close();
outputStream.close();
/************************************
* Simple byte writing
*******************/
FileOutputStream fos = null;
fos = new FileOutputStream(new File(repertoireDst + "\\" + intitule + "_V1_EcritureBytesSymple." + extension));
fos.write(output);
fos.flush();
fos.close();
/*************************************************
* Ecriture of bynary stream from blob
***********************************************/
InputStream is = blob.getBinaryStream();
FileOutputStream fos1 = new FileOutputStream(repertoireDst + "\\" + intitule + "_V2_BlobEcritDirectement.txt");
int b = 0;
while ((b = is.read()) != -1) {
fos1.write(b);
}
fos1.flush();
fos1.close();
/**************************************************************************
* Testing for base 64 encoding
************************************************************************/
File fichierDestinationTemp = new File(repertoireDst + "\\" + intitule + "_V3_FichierTxtTemp.txt");
File fichierDestinationTemp2 = new File(repertoireDst + "\\" + intitule + "_V4_FichierEncoderDecoder.txt");
File fichierDestinationTemp3 = new File(repertoireDst + "\\" + intitule + "_V5_FichierEncoder." + extension);
File fichierDestination = new File(repertoireDst + "\" + intitule + "." + extension);
PrintWriter writer = new PrintWriter(fichierDestinationTemp, "Cp1252");
writer.print(document2);
writer.close();
byte[] encodedBytes = Base64.getEncoder().encode(output);
String encodedString = new String(encodedBytes);
FileOutputStream fos2 = new FileOutputStream(fichierDestinationTemp3);
fos2.write(encodedString.getBytes());
fos2.flush();
fos2.close();
byte[] decodedBytes = Base64.getDecoder().decode(encodedString);
FileOutputStream fos3 = new FileOutputStream(fichierDestinationTemp2);
fos3.write(decodedBytes);
fos3.flush();
fos3.close();
Of course this creates my all sort of files, but non of the pdf files is readable. I guess I miss something. (And yeah I know that some parts I'm writing into .txt files but this was to see what I would get and hey, some of them where even in chinse...)
Any idea is welcome, wondering what I'm missing.
I finally found out what type of data was stored, the 0x78 is corresponding to zlib 4.0. This means I was able to inflate the data with an InflateOutputStream in java. Then I just had to save the data with a .pdf extension and everything was fine afterwards.
I am not very experienced and am trying to handle collisions in my hash table. However, it just skips over it and doesn't write it at all. I figured the while loop with the conditional if would take care of it... I have been playing around with it for a while now and feel like I am mixing everything up or losing my mind.
File file = new File("info.txt");
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null) {
temp = nhash.hashing(line,maxSize);
System.out.println(line + " " + " Hash key: " + temp);
int loc = (int)temp;
if(arr[loc] != null) // I FIGURED THIS WOULD SOLVE it
{ // THE ISSUE... But IT DOESN'T
while(arr[loc] != null) {
// System.out.println("Collision at [" + loc + "] with Data Item : [" + arr[loc] + "]");
loc++;
if(loc == maxSize)
loc = 0;
}
}else {
arr[loc] = line;
// System.out.println("Data Item[" + line + "] Stored in index [" + loc + "] of array.");
key[j] = loc;
j++;
}
}
My problem is that I want to see if a file is in a zip file. So I have made this code :
File zipf = new File(backupFolder, dfws.format(new Date()) + ".zip");
if (!zipf.exists()) zipf.createNewFile();
fs = new FileOutputStream(zipf);
ZipOutputStream zos = new ZipOutputStream(fs);
System.out.println("size : " + zipf.length());
if (zipf.length() > 0) {
ZipFile zf = new ZipFile(zipf);
System.out.println("entry : " + zf.getEntry(name));
if (zf.getEntry(name) != null) {
int index = 1;
while (zf.getEntry(index + "_" + name) != null) {
index++;
}
name = index + "_" + name;
}
zf.close();
}
System.out.println("index found : " + name);
But the problem is that the length of the file is always 0. And I can't create an instance of ZipFile if the zip file doesn't have files inside.
Thanks to RealSkeptic : I had to open the FileOutputStream after creating the ZipFile.
I'm trying to read a date (set of 6 integers) and temperature (double) from binary .dat file.
After multiple tries I finally got to the stage where the file is working, but it's returning int in the format I cannot recognize. Eg. date 2017-03-02 11:33 , and temperature 3.8 is read as:
Measure : 515840-1024-1024 2816 8512 241591910
temperature: 1.9034657819129845E185
Any ideas, how to change the code?
public void readFile() {
try {
DataInputStream dis = null;
BufferedInputStream bis = null;
try {
FileInputStream fis = new FileInputStream(fileLocation);
int b;
bis = new BufferedInputStream(fis);
dis = new DataInputStream(fis);
while ((b = dis.read()) != -1) {
System.out.println("Measure : " + dis.readInt() + "-"
+ dis.readInt() + "-" + dis.readInt() + " " +
dis.readInt() + " " + dis.readInt() + " "
+ dis.readInt() + " Temperature: "+ dis.readDouble());
}
} finally {
dis.close();
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (EOFException f) {
f.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} // readFile
while ((b = dis.read()) != -1) {
The problem is here. This reads and discards a byte of the file on every iteration, so all subsequent reads are out of sync.
The correct way to loop with a DataInputStream or ObjectInputStream is with a while (true) loop, and terminating it when read() returns -1, readLine() returns null, or readXXX() for any other X throws EOFException.
Note that you don't normally need to log or print a stack trace on EOFException, as it's a normal loop termination condition ... unless you had reason to expect more data, e.g. your file started with a record count that you haven't reached yet, which might indicate that the file was truncated and therefore corrupt.
Read an audio file, for example a wav file, then get its time length. Then get its bytes value from second by second, or by half a second. Like I have a 20 seconds wav and i will output its bytes[] by the time I specified. Because getting the bytes for all the length of the file takes very large of space.
This is me getting the bytes from the audio file, but i need just the bytes by its seconds. Any help?
FileInputStream s = new FileInputStream(Environment.getExternalStorageDirectory().getAbsolutePath()+"/audio_raw.wav");
BufferedInputStream b = new BufferedInputStream(s);
byte[] data = new byte[128];
while((bytes = b.read(data)) > 0)
{
for(int i = 0; i<bytes; i++)
{
unsigned = data[i] & 0xFF;
bw.write(unsigned+"+");
}
}
b.read(data);
b.close();
This is a function from a class that processes WAV files I use. You can see how it reads in the file and can extract some data about the WAV file. Perhaps it can assist you:
// read a wav file into this class
public boolean read()
{
DataInputStream inFile = null;
myData = null;
byte[] tmpLong = new byte[4];
byte[] tmpInt = new byte[2];
try
{
inFile = new DataInputStream(new FileInputStream(myPath));
//System.out.println("Reading wav file...\n"); // for debugging only
String chunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the ChunkSize
myChunkSize = byteArrayToLong(tmpLong);
String format = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
// print what we've read so far
//System.out.println("chunkID:" + chunkID + " chunk1Size:" + myChunkSize + " format:" + format); // for debugging only
String subChunk1ID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the SubChunk1Size
mySubChunk1Size = byteArrayToLong(tmpLong);
inFile.read(tmpInt); // read the audio format. This should be 1 for PCM
myFormat = byteArrayToInt(tmpInt);
inFile.read(tmpInt); // read the # of channels (1 or 2)
myChannels = byteArrayToInt(tmpInt);
inFile.read(tmpLong); // read the samplerate
mySampleRate = byteArrayToLong(tmpLong);
inFile.read(tmpLong); // read the byterate
myByteRate = byteArrayToLong(tmpLong);
inFile.read(tmpInt); // read the blockalign
myBlockAlign = byteArrayToInt(tmpInt);
inFile.read(tmpInt); // read the bitspersample
myBitsPerSample = byteArrayToInt(tmpInt);
// print what we've read so far
//System.out.println("SubChunk1ID:" + subChunk1ID + " SubChunk1Size:" + mySubChunk1Size + " AudioFormat:" + myFormat + " Channels:" + myChannels + " SampleRate:" + mySampleRate);
// read the data chunk header - reading this IS necessary, because not all wav files will have the data chunk here - for now, we're just assuming that the data chunk is here
String dataChunkID = "" + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte() + (char) inFile.readByte();
inFile.read(tmpLong); // read the size of the data
myDataSize = byteArrayToLong(tmpLong);
// read the data chunk
myData = new byte[(int) myDataSize];
inFile.read(myData);
// close the input stream
inFile.close();
}
catch (Exception e)
{
return false;
}
return true; // this should probably be something more descriptive
}