excel file not generating after UTF-8 encoding chosen - java

This part of my code was creating xls file successfuly
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
wb.write(fileOut);
fileOut.close();
when other part of the code had this statement ( which was before the above code )
in = new ByteArrayInputStream(theCell_00.getBytes(""));
But when I changed it to
in = new ByteArrayInputStream(theCell_00.getBytes("UTF-8"));
this part
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
wb.write(fileOut);
fileOut.close();
is not generating any xls file anymore.
I need to change the encoding to UTF-8 as I have done in ByteArrayInputStream line, so what should I do that the code still generates xls file.
In case you need it, the two parts are taken from this function.
public void getExcel() throws Exception {
try {
ByteArrayInputStream in = null;
FileOutputStream out = null;
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("new sheet");
/*
* KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); SecretKey key =
* kgen.generateKey(); byte[] encoded = key.getEncoded();
*
* IOUtils.write(encoded, new FileOutputStream(new
* File("C:\\Users\\abc\\Desktop\\key.txt")));
*/
FileInputStream fin = new FileInputStream("C:\\key.txt");
DataInputStream din = new DataInputStream(fin);
byte b[] = new byte[16];
din.read(b);
InputStream excelResource = new FileInputStream(path);
Workbook rwb = Workbook.getWorkbook(excelResource);
int sheetCount = rwb.getNumberOfSheets();
Sheet rs = rwb.getSheet(0);
int rows = rs.getRows();
int cols = rs.getColumns();
for (int i = 0; i < rows; i++) {
for (int j = 0; j < Col.length; j++) {
String theCell_00 = rs.getCell(j, i).getContents();
System.out.println("the Cell Content : " + theCell_00);
in = new ByteArrayInputStream(theCell_00.getBytes(""));
out = new FileOutputStream("c:\\Decrypted.txt");
try {
// System.out.println(b);
SecretKey key1 = new SecretKeySpec(b, "AES");
// Create encrypter/decrypter class
AESDecrypter encrypter = new AESDecrypter(key1);
encrypter.encrypt(new ByteArrayInputStream(theCell_00.getBytes()),
new FileOutputStream("temp.txt"));
// Decrypt
// encrypter.encrypt(,new FileOutputStream("Encrypted.txt"));
encrypter.decrypt(in, out);
try {
if (out != null)
out.close();
} finally {
if (in != null)
in.close();
}
// encrypter.decrypt(new
// ByteArrayInputStream(theCell_00.getBytes(Latin_1)),new
// FileOutputStream("c:\\Decrypted.txt"));
String filename = "c:\\Decrypted.txt";
BufferedReader bufferedReader = null;
try {
// Construct the BufferedReader object
bufferedReader = new BufferedReader(new FileReader(filename));
// System.out.println(bufferedReader.readLine());
String line = null;
while ((line = bufferedReader.readLine()) != null) {
// Process the data, here we just print it out
/*
* HSSFWorkbook wb = new HSSFWorkbook(); HSSFSheet sheet =
* wb.createSheet("new sheet"); HSSFRow row = sheet.createRow(2);
*/
// System.out.println(i);
HSSFRow row = sheet.createRow(i);
int s_col = 0;
row.createCell(s_col).setCellValue(line);
// s_col++;
// row.createCell(1).setCellValue(new Date());
FileOutputStream fileOut = new FileOutputStream("c:\\Decrypted.xls");
wb.write(fileOut);
fileOut.close();
// System.out.println(line);
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
// Close the BufferedReader
try {
if (bufferedReader != null)
bufferedReader.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
rwb.close();
} catch (Exception ex) {
ex.printStackTrace();
ex.getMessage();
}
}

What data types are expected by the call to AESDecrypter.decrypt? Does it have to take in a FileOutputStream object? Or can you pass in a Writer or other OutputStream?
I normally do something like this to write UTF-8 output:
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("c:\\Decrypted.txt"), "UTF-8"));

Related

How to write to an existing formatted excel file in java

I'm trying to write some data inside an existing formatted excel file (.xls).
Inside this file I have 3 sheets and I have to put the data inside the table of the second sheet.
I tried this:
String filename = "Report.xls";
HSSFWorkbook workbook = new HSSFWorkbook();
FileOutputStream fileOut = null;
try {
fileOut = new FileOutputStream(filename);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
int numberOfSheets = workbook.getNumberOfSheets();
System.out.println("Sheets found: " + numberOfSheets);
for(int i=0; i<numberOfSheets; i++) {
HSSFSheet sheet = workbook.getSheetAt(i);
String sheetName= workbook.getSheetName(i);
System.out.println("\n\nSheet with index: " + i
+ "/nHas name: " + sheetName);
}
try {
workbook.write(fileOut);
//closing the Stream
fileOut.close();
//closing the workbook
workbook.close();
} catch (IOException e1) {
e1.printStackTrace();
}
The Excel file has 3 sheets but I get this output:
Sheets found: 0
So I tried this:
String filename = "Report.xls";
InputStream inputStream = null;
Workbook workbook = null;
OutputStream outputStream = null;
try {
inputStream = new FileInputStream(filename);
workbook = WorkbookFactory.create(inputStream);
int Num = workbook.getNumberOfSheets();
System.out.println("Sheets found: " + Num);
for (int i = 0; i < Num; i++) {
Sheet sheet = workbook.getSheetAt(i);
Sheet s = workbook.getSheetAt(i);
String sheetName= s.getSheetName();
System.out.println("The sheet found has name: " + sheetName);
}
} catch (Exception error) {
error.getMessage();
}
But I get the same output..

Java - Prevent PrintWriter to overwrite the entire file everytime

I have a simulation program that needs to write certain results to a csv file very frequently during execution. I have found that there is something wrong with the printwriter which dramatically slows down running my program, as the output file is getting larger in size (near to 1 million rows). I doublt it's overwriting the entire file each time from the beginning, wheras I just need to append a single line at the bottom each time when it's being called. below is the code related to the writing fuctions.
one of the writing fuctions:
public void printHubSummary(Hub hub, String filePath) {
try {
StringBuilder sb = new StringBuilder();
String h = hub.getHub_code();
String date = Integer.toString(hub.getGs().getDate());
String time = hub.getGs().getHHMMFromMinute(hub.getGs().getClock());
String wgt = Double.toString(hub.getIb_wgt());
sb.append(h+","+date+","+time+","+wgt);
// System.out.println("truck print line: " + sb);
FileWriter.writeFile(sb.toString(),filePath);
}
catch (Exception e) {
System.out.println("Something wrong when outputing truck summary file!");
e.printStackTrace();
}
}
the file writer code: (should be where the problem is!)
public static boolean writeFile(String newStr, String filename) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filename);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
buf = buf.append(System.getProperty("line.separator"));
}
if (buf.length() > 0 && buf.charAt(0) == '\uFEFF') {
buf.deleteCharAt(0);
}
buf.append(filein);
fos = new FileOutputStream(file);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
An update on code modification. I have freezed the operations of repeatitively overwrting the entire file. It appears to solve the problem, but writing for sometime it's slowed down as well. Is it the best arrangement for wrting very large file? what other modifications can be done to make it even more efficient?
public static boolean writeFile1(String newStr, String filename) throws IOException {
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
File file = new File(filename);
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// for (int j = 1; (temp = br.readLine()) != null; j++) {
// buf = buf.append(temp);
// buf = buf.append(System.getProperty("line.separator"));
// }
// if (buf.length() > 0 && buf.charAt(0) == '\uFEFF') {
// buf.deleteCharAt(0);
// }
buf.append(filein);
fos = new FileOutputStream(file,true);
byte[] unicode = {(byte)0xEF, (byte)0xBB, (byte)0xBF};
fos.write(unicode);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
Provide a second argument to the FileOutputStream constructor to specify whether or not to use append mode, which will add to the end of the file rather than overwriting it.
fos = new FileOutputStream(file, true);
Alternatively, you could create a single static PrintWriter in append mode, which will probably be faster as it reduces garbage collection.
Use the Files / Path / Java NIO2 which is richer: the code below would need Java 7 at least.
Path path = Paths.get(filename);
try (BufferedWriter bw = Files.newBufferedWriter(
path, StandardCharsets.UTF_8, StandardOpenOption.APPEND, StandardOpenOption.CREATE, StandardOpenOption.WRITE)) {
bw.append(filein);
bw.newLine();
}
Your cue here is the StandardOpenOption.
You will probably have to do some additional code before to write the Unicode part (and fix the StandardCharsets.UTF_8):
if (Files.notExists(path)) {
Files.write(path, new byte[] {(byte)0xEF, (byte)0xBB, (byte)0xBF});
}
Also, try to not use StringBuffer in a local method, use StringBuilder: you don't need synchronisation most of the time.

Data not getting saved after copying data from one sheet to another using java

I am using below code to copy couple of columns from one sheet to another in excel. But data is getting copied to new sheet but when i open that file and try to close it, it asks do you want to save it? What should i do.
FileInputStream fis;
try {
fis = new FileInputStream("C:\\Banks\\SBI.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet Sheet1 = wb.getSheet("new sheet");
XSSFSheet nfrntSheet = wb.createSheet("Original");
int n = Sheet1.getLastRowNum();
System.out.println(n);
for(int i = 0;i<n+11;i++)
{
XSSFRow r = nfrntSheet.createRow(i);
Cell c = r.createCell(0);
c.setCellFormula("'new sheet'!A"+(i-9));
nfrntSheet.autoSizeColumn(0);
}
for(int i = 0;i<n+11;i++)
{
XSSFRow r = nfrntSheet.getRow(i);
Cell c = r.createCell(1);
c.setCellFormula("'new sheet'!C"+(i-9));
nfrntSheet.autoSizeColumn(1);
}
for(int i = 0;i<=7;i++)
{
nfrntSheet.setColumnWidth(i, 5000);
}
nfrntSheet.setColumnWidth(1, 12000);
nfrntSheet.setColumnWidth(17, 30000);
fis.close();
FileOutputStream stream= new FileOutputStream(new File("C:\\Banks\\SBI.xlsx"));
wb.write(stream);
stream.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(CommandLineApp.class.getName()).log(Level.SEVERE, null, ex);
}

converting csv to excel through java

I have to convert CSV to XLS format through Java POI since I am doing some manipulations with XLS sheets through POI. Below is my code:
File file = new File("C:\\abc.csv");
FileInputStream fin = null;
fin = new FileInputStream(file);
HSSFWorkbook workbook = new HSSFWorkbook(fin);
HSSFSheet firstSheet1 = workbook.getSheetAt(0);
Now I want to write a fuctions, lets say method name is convertcsvtoexcel which will accept the file obj and in return it will be give me converted XLS file that file will be stored in my C: drive with the name abcout.xls and later on I will be passing it to workbook as shown. I have tried the following code. Please advise how I can custoise it to make it fittable for my piece of code.
ArrayList arList = null;
ArrayList al = null;
String fName = "test.csv";
String thisLine;
int count = 0;
FileInputStream file = null;
file = new FileInputStream(new File("C:\\abc.csv"));
//FileInputStream fis = new FileInputStream(file);
DataInputStream myInput = new DataInputStream(file);
int i = 0;
arList = new ArrayList();
while ((thisLine = myInput.readLine()) != null) {
al = new ArrayList();
String strar[] = thisLine.split(",");
for (int j = 0; j < strar.length; j++) {
al.add(strar[j]);
}
arList.add(al);
System.out.println();
i++;
}
try {
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
for (int k = 0; k < arList.size(); k++) {
ArrayList ardata = (ArrayList) arList.get(k);
HSSFRow row = sheet.createRow((short) 0 + k);
for (int p = 0; p < ardata.size(); p++) {
HSSFCell cell = row.createCell((short) p);
String data = ardata.get(p).toString();
if (data.startsWith("=")) {
cell.setCellType(Cell.CELL_TYPE_STRING);
data = data.replaceAll("\"", "");
data = data.replaceAll("=", "");
cell.setCellValue(data);
} else if (data.startsWith("\"")) {
data = data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_STRING);
cell.setCellValue(data);
} else {
data = data.replaceAll("\"", "");
cell.setCellType(Cell.CELL_TYPE_NUMERIC);
cell.setCellValue(data);
}
//*/
// cell.setCellValue(ardata.get(p).toString());
}
System.out.println();
}
FileOutputStream fileOut = new FileOutputStream("C:\\abcout.xls");
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated");
} catch (Exception ex) {
ex.printStackTrace();
} //main method end
public static void csvToXLSX() {
try {
String csvFileAddress = "test.csv"; //csv file address
String xlsxFileAddress = "test.xlsx"; //xlsx file address
XSSFWorkbook workBook = new XSSFWorkbook();
XSSFSheet sheet = workBook.createSheet("sheet1");
String currentLine=null;
int RowNum=0;
BufferedReader br = new BufferedReader(new FileReader(csvFileAddress));
while ((currentLine = br.readLine()) != null) {
String str[] = currentLine.split(",");
RowNum++;
XSSFRow currentRow=sheet.createRow(RowNum);
for(int i=0;i<str.length;i++){
currentRow.createCell(i).setCellValue(str[i]);
}
}
FileOutputStream fileOutputStream = new FileOutputStream(xlsxFileAddress);
workBook.write(fileOutputStream);
fileOutputStream.close();
System.out.println("Done");
} catch (Exception ex) {
System.out.println(ex.getMessage()+"Exception in try");
}
}

How can I set the save path for new files in JFileChooser?

I have a dialog using JFileChooser. When I save a file by FileOutputStream, I want to save it as file.txt in the path which the user want. But it always saves in c:/user/Document.
Here is the code:
DownLoadDialog downloadDialog = new DownLoadDialog();
int result = downloadDialog.showSaveDialog(queryPanel);
if (result == downloadDialog.APPROVE_OPTION) {
File file = downloadDialog.getSelectedFile();
//String parth =file.getPath();
//System.out.println(parth);
//if(file.exists()) {
//int response = JOptionPane.showConfirmDialog (null,
// "Overwrite existing file?","Confirm Overwrite",
// JOptionPane.OK_CANCEL_OPTION,JOptionPane.QUESTION_MESSAGE);
//if(response == JOptionPane.OK_OPTION) {}
//} else {
if (resultGoogleSearch > 0) {
{
String parth = new File(downloadDialog.getSelectedFile().
getAbsolutePath().concat(".txt")).toString();
System.out.println(parth);
for (int i = 0; i < resultGoogleSearch; i++) {
String[] temp = googleSearchResult.get(i).split("<br>");
//String resultURL = temp[0];
//File dir = downloadDialog.getCurrentDirectory();
try {
FileOutputStream googleReuslt = new FileOutputStream(
downloadDialog.getSelectedFile().getAbsolutePath()
+ ".txt");
OutputStreamWriter writer = new
OutputStreamWriter(googleReuslt);
BufferedWriter buffer = new BufferedWriter(writer);
writer.write(temp[0]);
writer.close();
buffer.close();
} catch (FileNotFoundException fEx) {
} catch (IOException ioEx) {
}
}
}
JOptionPane.showMessageDialog(IDRSApplication.idrsJFrame,
IDRSResourceBundle.res.getString("successful"));
}
The problem is here: why can't I set path for new file?
FileOutputStream googleReuslt = new FileOutputStream(
downloadDialog.getSelectedFile().getAbsolutePath() + ".txt");
OutputStreamWriter writer = new OutputStreamWriter(googleReuslt);
BufferedWriter buffer = new BufferedWriter(writer);
writer.write(temp[0]);
writer.close();
buffer.close();
The code you provided works as you would expect. (At least under linux.)
I suggest you do a SSCCE and update your question.

Categories