The headers of the table are generated but not the data.
I tried everything but somehow either the data is haphazard or blank
detail: query to excel
How to format below code?
import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class QA2Excel {
/**
* #param paramArrayOfString
* #throws Exception
*/
public static void main(String[] paramArrayOfString)
throws Exception
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
String str1 = "jdbc:oracle:thin:#indlin076:1521:VELABP1";
String str2 = "VELDB2";
String str3 = "VELDB2";
Connection localConnection = DriverManager.getConnection(str1, str2, str3);
HSSFWorkbook localHSSFWorkbook = new HSSFWorkbook();
localConnection.setAutoCommit(false);
Statement localStatement = localConnection.createStatement();
String str4 = "VELDBO2";
String str5 = "VELDBO2";
String str6 = "#DB14";
String filename="C://Users/debankad/Desktop/empha.xls";
FileReader localFileReader = new FileReader("C://Users/debankad/Desktop/QueriesOfQa.txt");
BufferedReader localBufferedReader = new BufferedReader(localFileReader);
String str11;
String paramString= "";
//StringBuilder stringBuilder = new StringBuilder();
while ((str11 = localBufferedReader.readLine()) != null)
{
if (str11.startsWith("--EPC")){
paramString = str11.replace("--","").toUpperCase();
System.out.println("PARAMSTRING" + paramString);
}
if (!str11.endsWith(";")){
System.out.println(str11);
String str14 = str11;
if (str11 != null && !str11.isEmpty() && !str11.startsWith("--") && !str11.startsWith("//")){
paramString = paramString + 1;
ResultSet localResultSet = localStatement.executeQuery(str11);
int i = recordCountinResultSet(localResultSet);
HSSFSheet localHSSFSheet = localHSSFWorkbook.createSheet(paramString);
HSSFRow localHSSFRow = localHSSFSheet.createRow(0);
ResultSetMetaData localResultSetMetaData = localResultSet.getMetaData();
for (int k = 0; k < localResultSetMetaData.getColumnCount(); k++){
localHSSFRow.createCell((short)k).setCellValue(localResultSetMetaData.getColumnLabel(k + 1));
for (int k1 = 1; localResultSet.next(); k1++)
{
localHSSFRow = localHSSFSheet.createRow((short)k1);
for (int j = 0; j < localResultSetMetaData.getColumnCount(); j++)
localHSSFRow.createCell((short)j).setCellValue(localResultSet.getString(j + 1));
}
}
FileOutputStream fileOut = new FileOutputStream(filename);
localHSSFWorkbook.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
if (i == 0)
{
System.out.println("QA Passed");
}
else if (i >= 1)
{
System.out.println("QA Failed");
}
else
{
System.out.println("No such Query");
}
}
}
//selectTableCreation(localStatement,localFileReader);
// String str8 = str2.substring(str2.lastIndexOf(" "), str2.length()).trim().toUpperCase();
// System.out.println(str8);
}} catch (Exception E){
E.printStackTrace();
}
}
#SuppressWarnings("rawtypes")
public static List selectTableCreation(Statement paramStatement, FileReader paramFileReader)
{
ArrayList<ResultSet> localArrayList = new ArrayList<ResultSet>();
try
{
BufferedReader localBufferedReader = new BufferedReader(paramFileReader);
String str1;
while ((str1 = localBufferedReader.readLine()) != null)
{
String str2 = str1;
try
{
ResultSet localResultSet = paramStatement.executeQuery(str2);
System.out.println("Result Set Obtained");
localArrayList.add(localResultSet);
}
catch (Exception localException2)
{
}
}
}
catch (Exception localException1)
{
System.out.println("Exception caught as::" + localException1.getMessage());
}
return localArrayList;
}
#SuppressWarnings("deprecation")
public static void writeToFile(HSSFWorkbook paramHSSFWorkbook, ResultSet paramResultSet, String paramString)
throws Exception
{
HSSFSheet localHSSFSheet = paramHSSFWorkbook.createSheet(paramString);
HSSFRow localHSSFRow = localHSSFSheet.createRow(0);
ResultSetMetaData localResultSetMetaData = paramResultSet.getMetaData();
for (int i = 0; i < localResultSetMetaData.getColumnCount(); i++)
localHSSFRow.createCell((short)i).setCellValue(localResultSetMetaData.getColumnLabel(i + 1));
for (int i = 1; paramResultSet.next(); i++)
{
localHSSFRow = localHSSFSheet.createRow((short)i);
for (int j = 0; j < localResultSetMetaData.getColumnCount(); j++)
localHSSFRow.createCell((short)j).setCellValue(paramResultSet.getString(j + 1));
}}
public static int recordCountinResultSet(ResultSet paramResultSet)
{
int i = 0;
try
{
while (paramResultSet.next())
i++;
}
catch (Exception localException)
{
System.out.println("Exception obtained as" + localException.getMessage());
}
return i;
}
}
I believe you have ended a parentheses at wrong position.
Try this and it should work:
for (int k = 0; k < localResultSetMetaData.getColumnCount(); k++)
{
localHSSFRow.createCell((short)k).setCellValue(localResultSetMetaData.getColumnLabel(k + 1));
} //This should end here
for (int k1 = 1; localResultSet.next(); k1++)
{
localHSSFRow = localHSSFSheet.createRow((short)k1);
for (int j = 0; j < localResultSetMetaData.getColumnCount(); j++)
{
localHSSFRow.createCell((short)j).setCellValue(localResultSet.getString(j + 1));
}
}
Related
I have already uploaded the excel file in my local directory but the problem is that I can't read it from that location.
I am using struts 1.1 ,db2.
package mj.eps.action;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Vector;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import com.mj.eps.dto.business.auction.UploadObject;
import com.mj.eps.dto.training.IndexValueReportObject;
import com.mj.eps.framework.util.FileScaner;
import com.mj.eps.framework.util.IConstant;
public class IndexValueAction extends EPSBaseAction{
public IndexValueAction() {
super();
}
#SuppressWarnings("unchecked")
#Override
public ActionForward execute(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
throws Exception {
Vector<String> vector = new Vector<String>();
ActionErrors errors = new ActionErrors();
ActionForward forward = new ActionForward();
try{
String contentType = request.getContentType();
if ((contentType != null)
&& (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in =
new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead =
in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary =
contentType.substring(
lastIndex + 1,
contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos =
(
(file.substring(0, boundaryLocation))
.getBytes())
.length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
Date dt = new Date();
SimpleDateFormat df = new SimpleDateFormat();
df.applyPattern("dd-MM-yy hh-mm-ss");
saveFile = saveFile.substring(0, saveFile.indexOf("."))+ "-"+ df.format(dt)+ ".xls";
String uploadFilePath = "";
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if(endPos > dataBytes.length )
endPos = dataBytes.length;
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String[]> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId=0;
try {
File outFile = new File(uploadFilePath + saveFile);
ServletConfig config = getServlet();
ServletContext sc = config.getServletContext();
boolean retVal = false;
boolean exists = true;
String filepath = outFile.getAbsolutePath();
String realPath = sc.getRealPath("virusCheck.properties");
exists = FileScaner.loadProperty(realPath);
if (exists) {
retVal = FileScaner.checkVirus(realPath, filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>Virus found!!"));
}
if (retVal) {
retVal = FileScaner.checkFileSign(filepath);
if (!retVal) {
FileScaner.cleanFile(filepath);
errors.add(
ActionErrors.GLOBAL_ERROR,
new ActionError(
"errors.dynamic",
"<li>File type not supported!!"));
}
}
}
else {
}
if (retVal) {
}
if (errors.isEmpty())
{
***FileInputStream inputStream=new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows=read_sheet.getRows();
for (int j=1;j<rows;j++){
String[] fields=new String[4];
for(int i=0;i<fields.length;i++)
{
Cell cell=read_sheet.getCell(i,j);
fields[i]=cell.getContents().trim();
if(fields[0] != null ){
try{
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
}else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
}
catch(Exception e1)
{
int k=i+1;
errorVector.add("Invalid data at field "+k);
System.out.println(" err1 :" + e1.toString());
errorId = 1;
}
}
}
if(!(fields[0] == null || (fields[0].trim().equals(""))))
{
rowVector.add(fields);
}
else{
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
if (errorId == 0) {
int row = 0;
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
IndexValueReportObject indexValueReportObj =
new IndexValueReportObject();
String[] fields =
rowVector.elementAt(i);
System.out.println("abc>>>>>"+fields[0]);
System.out.println("abc>>>>>>>>>>>>>"+fields[1]);
System.out.println("abc>>>>>>>>>>>>>>>>>"+fields[2]);
System.out.println("abc>>>>>>>>>>>>>>>>>>>>>>>"+fields[3]);
try{
indexValueReportObj
.setDate(
Timestamp.valueOf(fields[0]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Date at row " + (row+1));
}
try{
indexValueReportObj
.setPlatts(
new BigDecimal(fields[1]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Platts Value at row " + (row+1));
}
try{
indexValueReportObj
.setArgus(
new BigDecimal(fields[2]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid Argus Value at row " + (row+1));
}
try{
indexValueReportObj
.setTsi(
new BigDecimal(fields[3]));
}catch (Exception e1)
{
row = i + 1;
vector.add("Invalid TSI value at row " + (row+1));
}
indexObjectVector.add(
indexValueReportObj);
}
} else {
vector.add(
"No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription =
(String) errorVector.get(k);
vector.add(errorDescription);
}
}
String filePathAndName=uploadFilePath + saveFile;
System.out.println("indexObjectVector"+indexObjectVector);
request.setAttribute(
IConstant.INDEX_OBJECT_VECTOR,
indexObjectVector);
request.getSession().setAttribute(
IConstant.FILE_NAME,
filePathAndName);
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
} else {
vector.add("File Type mismatch ");
}
} catch (Exception e) {
vector.add("No excel has been selected ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
forward = mapping.findForward("failureUpload");
} else {
forward = mapping.findForward("success");
}
return forward;
}
}
In Workbook portion I want to read the excel file from local directory. When I run this code in debug mode, the control is going into exception block and forward it in my success page. So can some one please help me with this? I put sysout in that portion but nothing shows. I am using JXl for excel read and write. My confusion is in 3 star portion.
Not an answer, but a partial refactoring.
This is an abomination of an action. There is zero way this should have ever passed any code review:
Actions and business logic should be completely separate.
Methods should be responsible for a single responsibility. This method:
Checks content type (arguably reasonable since that's web-related)
Manually parses the form (inexcusable; use a library)
Processes an Excel file (inexcusable; extract) which in turn:
Validates against business logic
Converts Excel values to BO values
The amount of un-equivalent work the action does defies explanation. This makes it essentially impossible to reason about, debug, fix, or anything. The below is a very rough start of refactoring, but you have another day or two of work to properly isolate levels of functionality and error handling (which is wrong, by the way, because you never check vector, possibly the worst-named variable in history, for errors, it's just thrown away?!?!?!)
public class IndexValueAction extends EPSBaseAction {
public IndexValueAction() {
super();
}
boolean isValidContentType(contentType) {
return (contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)
}
String readContent(request) throws Exception {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
totalBytesRead += in.read(dataBytes, totalBytesRead, formDataLength);
}
return new String(dataBytes);
}
void scanFile(realPath, outFilePath, errors) throws Exception {
if (!FileScanner.loadProperty(realPath)) {
return false;
}
if (!FileScanner.cleanFile(outFilePath)) {
FileScaner.cleanFile(outFilePath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>Virus found!!"));
return;
}
if (!FileScanner.checkFileSign(outFilePath)) {
FileScaner.cleanFile(filepath);
errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("errors.dynamic", "<li>File type not supported!!"));
}
}
IndexValueReportObject loadIndexValueReportObject(String[] fields, int i, Vector<String> vector) {
IndexValueReportObject indexValueReportObj = new IndexValueReportObject();
try {
indexValueReportObj.setDate(Timestamp.valueOf(fields[0]));
} catch (Exception e) {
vector.add("Invalid Date at row " + (i + 2));
}
try {
indexValueReportObj.setPlatts(new BigDecimal(fields[1]));
} catch (Exception e) {
vector.add("Invalid Platts Value at row " + (i + 2));
}
try {
indexValueReportObj.setArgus(new BigDecimal(fields[2]));
} catch (Exception e) {
vector.add("Invalid Argus Value at row " + (i + 2));
}
try {
indexValueReportObj.setTsi(new BigDecimal(fields[3]));
} catch (Exception e) {
vector.add("Invalid TSI value at row " + (i + 2));
}
return indexValueReportObj;
}
#Override
#SuppressWarnings("unchecked")
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {
Vector<String> vector = new Vector<String>();
if (!isValidContentType(request.getContentType())) {
vector.add("File Type mismatch");
return mapping.findForward("failureUpload");
}
String file;
try {
file = readContent(request);
} catch (Exception e) {
vector.add("No excel has been selected");
return mapping.findForward("failureUpload");
}
ActionErrors errors = new ActionErrors();
try {
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1, contentType.length());
int pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = file.substring(0, boundaryLocation).getBytes().length;
Vector<IndexValueReportObject> indexObjectVector = new Vector<IndexValueReportObject>();
SimpleDateFormat df = new SimpleDateFormat("dd-MM-yy hh-mm-ss");
String fileSuffix = "-" + df.format(new Date()) + ".xls";
saveFile = saveFile.substring(0, saveFile.indexOf(".")) + fileSuffix;
ServletContext sc1 = request.getSession().getServletContext();
Properties properties = new Properties();
String realPath1 = sc1.getRealPath("serverPath.properties");
FileInputStream fis = new FileInputStream(realPath1);
properties.load(fis);
String uploadFilePath = properties.getProperty("fileUpload.path");
FileOutputStream fileOut = new FileOutputStream(uploadFilePath + saveFile);
System.out.println(uploadFilePath);
if (endPos > dataBytes.length) {
endPos = dataBytes.length;
}
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
Vector<String []> rowVector = new Vector<String[]>();
Vector<Object> errorVector = new Vector<Object>();
UploadObject uploadObject = new UploadObject();
int errorId = 0;
try {
ServletContext sc = getServlet().getServletContext();
String realPath = sc.getRealPath("virusCheck.properties");
File outFile = new File(uploadFilePath + saveFile);
String outFilePath = outFile.getAbsolutePath();
scanFile(realPath, outFilePath, errors);
if (errors.isEmpty()) {
FileInputStream inputStream = new FileInputStream(uploadFilePath + saveFile);
Workbook w = Workbook.getWorkbook(inputStream);
Sheet read_sheet = w.getSheet(0);***
int rows = read_sheet.getRows();
for (int j = 1; j < rows; j++) {
String[] fields = new String[4];
for(int i = 0; i < fields.length; i++) {
Cell cell = read_sheet.getCell(i, j);
fields[i] = cell.getContents().trim();
if (fields[0] != null) {
try {
if (fields[i].indexOf(".") > 0) {
if (i != 1) {
fields[i] = fields[i];
} else {
fields[i].substring(0, fields[i].indexOf("."));
}
}
} catch(Exception e1) {
int k = i+1;
errorVector.add("Invalid data at field " + k);
errorId = 1;
}
}
}
if (!(fields[0] == null || (fields[0].trim().equals("")))) {
rowVector.add(fields);
} else {
break;
}
}
uploadObject.setErrorId(errorId);
uploadObject.setErrorVector(errorVector);
uploadObject.setRowVector(rowVector);
if (errorId == 0) {
if (rowVector.size() > 0) {
for (int i = 0; i < rowVector.size(); i++) {
String[] fields = rowVector.elementAt(i);
indexObjectVector.add(loadIndexValueReportObject(loadIndexValueReportObject(fields, i, vector)));
}
} else {
vector.add("No Bidder is created in the excel file ");
}
} else {
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
}
} catch (Exception e1) {
errorId = uploadObject.getErrorId();
rowVector = uploadObject.getRowVector();
errorVector = uploadObject.getErrorVector();
for (int k = 0; k < errorVector.size(); k++) {
String errorDescription = (String) errorVector.get(k);
vector.add(errorDescription);
}
}
request.setAttribute(IConstant.UPLOAD_MESSAGE, "uploaded");
request.setAttribute(IConstant.INDEX_OBJECT_VECTOR, indexObjectVector);
request.getSession().setAttribute(IConstant.FILE_NAME, uploadFilePath + saveFile);
} catch (Exception e1) {
vector.add("File name or sheet name error ");
}
if (!errors.isEmpty()) {
request.setAttribute(IConstant.ERROR_VECTOR, errors);
return mapping.findForward("failureUpload");
}
return mapping.findForward("success");
}
}
I am new in java. Firstly, I'm sorry for my English. I wrote a code to merge two different txt files in the mergedFile.txt with determined data from the data1.txt and data2.txt. I create 5 different arrays to use them better but I cannot learn the length of words in the textfiles so arrays are using determined parameter. If I want to add another student, this codes don't work. Can you help me?
data1.txt
ID,Name,LastName,Department
12345,John,Samon,Computer Science
14524,David,Souza,Electric and Electronic
.
.
data2.txt
ID,Q1,Q2,Q3,Midterm,Final
12345,100,90,75,89,100
14524,80,70,65,15,90
.
margedFile.txt
ID,Name,Q_Average,Midterm,Final,Department
12345,John,88.3,89,100,Computer Science
14524,David,67.0,100,70,Electric and Electronic
This is ReadData Class
import java.io.FileInputStream;//import java.io library
import java.util.Scanner;//import scanner library
public class ReadData {
public static String[] Read(String filename,String filename2) {
Scanner scan = null;
Scanner scan1 = null;/
FileInputStream input1 = null;
FileInputStream input = null;
String[] result = new String[3];
try {
input = new FileInputStream(filename);
scan = new Scanner(input);
input1 = new FileInputStream(filename2);
scan1 = new Scanner(input1);
String[][] myArray = new String[4][4];
String[][] myArray1 = new String[4][6];
while(scan.hasNext() || scan1.hasNext()) {
for (int i = 0; i < myArray.length; i++) {
String[] split =
scan.nextLine().trim().split(",");
for (int j = 0; j < split.length; j++)
{
myArray[i][j] = split[j];
}
}
for (int i = 0; i < myArray1.length; i++) {
String[] split1 = scan1.nextLine().trim().split(",");
for (int j = 0; j < split1.length; j++) {
myArray1[i][j] = split1[j];
}
}
}
int[][] quiz = new int[3][3];
double[] average = new double[3];
int sum = 0;
double averagee = 0;
for (int i = 0; i < quiz.length; i++) {
for (int j = 0; j < quiz.length; j++) {
quiz[i][j] = Integer.parseInt(myArray1[i+1][j+1]);
sum += quiz[i][j];
}
averagee = sum/quiz.length;
average[i] = averagee;
sum = 0;
}
for (int i = 1; i < myArray1.length; i++) {
for (int j = 1; j < myArray1.length; j++) {
if(myArray[i][0].equalsIgnoreCase(myArray1[j][0])) {
result[i-1] = "\n" + myArray[i][0] + " "+ myArray[i][1] + " " + (average[j-1]) +" "+ myArray1[j][4] +" " + myArray1[j][5] + " "+ myArray[i][3];
//System.out.println(Arrays.deepToString(myArray[i]) + " " + Arrays.deepToString(myArray1[j]));
}
}
}
//System.out.println(Arrays.deepToString(quiz));
//System.out.println(Arrays.toString(average));
}
catch(Exception e) {
System.out.println(e);
}
return result;
}
}
This is WriteData class
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.Arrays;
public class WriteData extends ReadData {
void Write(String filename) {
PrintWriter writer = null;
FileOutputStream output = null;
try {
output = new FileOutputStream(filename);
writer = new PrintWriter(output);
writer.print("ID,Name,Q_Average,Midterm,Final,Department ");
writer.print(Arrays.toString(Read("data1.txt",
"data2.txt")));
writer.flush();
writer.close();
} catch (Exception e) {
// TODO: handle exception
}
}
}
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
public class database {
String fileName;
Scanner input;
String[][] data;
List<String> useful_list;
List<String> records;
ArrayList<Object> handles;
public database(String fileName) {
this.fileName = fileName;
}
public void openFile() {
try {
input = new Scanner(new File(fileName));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
return;
}
}
public void readRecords() {
// Read all lines (records) from the file into an ArrayList
records = new ArrayList<String>();
try {
while (input.hasNext())
records.add(input.nextLine());
} catch (Exception e) {
// TODO: handle exception
}
}
public void parseFields() {
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = records.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row = 0;
for (String record : records) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row] = new String[cols]; // create columns for current row
int col = 0;
while (tokens.hasMoreTokens()) {
data[row][col] = tokens.nextToken().trim();
col++;
}
row++;
}
}
public static void main(String[] args) {
String filename = null;
String[] values = new String[4];
String input = null;
BufferedReader reader = new BufferedReader(new InputStreamReader(
System.in));
try {
filename = reader.readLine();
input = reader.readLine();
values = input.split(",");
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
int[] input1;
input1 = new int[4];
try {
for (int j = 0; j < values.length; j++) {
input1[j] = Integer.parseInt(values[j]);
}
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("Invalid Input");
return;
}
if (input1[0] >= 4 || input1[0] <= 0) {
System.out.println("Invalid Input");
return;
}
database file1 = new database(filename);
file1.openFile();
file1.readRecords();
file1.parseFields();
file1.search(input1[1]);
if (file1.useful_list.size() == 0) {
System.out.println("Data Unavailable");
return;
}
file1.sortarray(input1[0] - 1);
int width = input1[2];
int skip = (input1[3] - 1) * width;
Iterator<Object> it = file1.handles.iterator();
for (int i = 1; i <= skip; i++) {
if (it.hasNext()) {
it.next();
} else {
System.out.println("Data Unavailable");
return;
}
}
for (int j = 1; j <= width && it.hasNext(); j++) {
String[] a = (String[]) it.next();
for (int i = 0; i < a.length; i++)
if(i<a.length-1)
System.out.print(a[i] + ",");
else
System.out.print(a[i]);
System.out.println();
}
}
void sortarray(final int index) {
handles = new ArrayList<Object>();
for (int i = 0; i < data.length; i++)
handles.add(data[i]);
Collections.sort(handles, new Comparator<Object>() {
public int compare(Object o1, Object o2) {
String[] a = (String[]) o1;
String[] b = (String[]) o2;
if (index == 1 || index == 0) {
int left = Integer.parseInt(a[index]);
int right = Integer.parseInt(b[index]);
return Integer.compare(left, right); //Line 165
} else {
if (a.length == 0 && b.length == 0)
return 0;
if (a.length == 0 && b.length != 0)
return 1;
if (a.length != 0 && b.length == 0)
return -1;
return a[index].compareTo(b[index]);
}
}
public boolean equals(Object o) {
return this == o;
}
});
}
void search(int searchs) {
useful_list = new ArrayList<String>();
for (int row = 0; row < data.length; row++) {
if (Integer.parseInt(data[row][0]) == searchs) {
// store in array list
useful_list.add(data[row][0] + "," + data[row][1] + ","
+ data[row][2] + "," + data[row][3]);
}
}
if (useful_list.size() == 0) {
return;
}
String delimiter = ",\n";
// Create two-dimensional array to hold data (see Deitel, p 313-315)
int rows = useful_list.size(); // #rows for array = #lines in file
data = new String[rows][]; // create the rows for the array
int row1 = 0;
for (String record : useful_list) {
StringTokenizer tokens = new StringTokenizer(record, delimiter);
int cols = tokens.countTokens();
data[row1] = new String[cols]; // create columns for current row
int col1 = 0;
while (tokens.hasMoreTokens()) {
data[row1][col1] = tokens.nextToken().trim();
col1++;
}
row1++;
}
}
}
this code is working fine on eclipse .
but if i submit it for my online compilation ..
it shows compile time error.
error message
*database.java 163 cannotfindsymbolsymbol methodcompare int int location class java.lang.Integer return Integer.compare left right ;^1error*
Integer.compare was introduced to Java in version 1.7. Chances are that the online compiler has an earlier version of the compiler
Integer.compare(int,int) was introduced in Java 1.7. I expect you are seeing that error because Java 6 or earlier is used to compile the code. The docs. themselves (linked above) show how to do it for earlier Java (you should consult them at times like this).
Integer.valueOf(x).compareTo(Integer.valueOf(y))
here i am trying to use Buffered reader to read text file and create table in database, but Buffered reader reads only First Name from my text file. May i know What is wrong in my code... It WORKS Fine In MySQL , but in SQL Server it reads only first name.
Text File: http://textuploader.com/?p=6&id=vrQs9
Whole Code :
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.DatabaseMetaData;
import com.mysql.jdbc.Statement;
import java.io.*;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.table.*;
import java.sql.DriverManager;
import java.sql.ResultSet;
public class Stackq extends AbstractTableModel {
Vector<String> data;
Vector columns;
public Stackq() {
String line;
data = new Vector<String>();
columns = new Vector();
int count = 0;
try {
FileInputStream fis = new FileInputStream("D:/joy/text/registration.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
StringTokenizer st1 = new StringTokenizer(br.readLine(), "\t");
while (st1.hasMoreTokens()) {
columns.addElement(st1.nextToken());
count++;
}
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "\t");
for (int i = 0; i < count; i++) {
if (st2.hasMoreTokens()) {
data.addElement(st2.nextToken());
} else {
data.addElement("");
}
}
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void setValueAt(Object value, int row, int col) {
data.setElementAt((String) value, col);
fireTableCellUpdated(row, col);
}
public boolean isCellEditable(int row, int col) {
//if (4 == col){
return true;
}
//else {
// return false;
// }
//}
//public void insertData(Object[] values){
// data.add(new Vector());
//for(int i =0; i<values.length; i++){
//((Vector) data.get(data.size()-1)).add(values[i]);
//}
//fireTableDataChanged();
// }
public void removeRow(int row) {
data.removeElementAt(row);
fireTableDataChanged();
}
public int getRowCount() {
return data.size() / getColumnCount();
}
public int getColumnCount() {
return columns.size();
}
public Object getValueAt(int rowIndex, int columnIndex) {
return (String) data.elementAt((rowIndex * getColumnCount())
+ columnIndex);
}
public String getColumnName(int i) {
return (String) columns.get(i);
}
public static void main(String args[]) {
Stackq model = new Stackq();
JTable table = new JTable();
table.setModel(model);
JScrollPane scrollpane = new JScrollPane(table);
JPanel panel = new JPanel();
panel.add(scrollpane);
JFrame frame = new JFrame();
frame.add(panel, "Center");
frame.pack();
frame.setVisible(true);
StringBuffer sbTableData = new StringBuffer();
for (int row = 0; row < table.getRowCount(); row++) {
for (int column = 0; column < table.getColumnCount(); column++) {
sbTableData.append(table.getValueAt(row, column)).append("\t");
}
sbTableData.append("\n");
}
System.out.println(sbTableData);
try {
PrintWriter f = new PrintWriter(new BufferedWriter(new FileWriter("D:/joy/text/registration6.txt", true)));
//f.println(sbTableData+"\t"+"n");
f.close();
} catch (IOException e) {
e.printStackTrace();
}
String readstr1 = null;
int row = table.getRowCount();
int column = table.getColumnCount();
for (int j = 0; j < row; j++) {
for (int i = 0; i < column; i++) {
//System.out.println(table.getValueAt(j, i));
readstr1 = (String) table.getValueAt(j, i);
//System.out.println(readstr);
}
}
try {
// FILE READ AND TABLE CREATE
String tname = "example11199";
String dbname = "DB";
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
java.sql.Connection conn = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;user=SOFTWARE\joy;databaseName=DB;integratedSecurity=true;");
java.sql.Statement stmt = conn.createStatement();
// stmt=conn.createStatement();
//System.out.println("connect");
//System.out.println(readstr1);
FileInputStream fstr = new FileInputStream("D:/joy/text/registration6.txt");
// Get the object of DataInputStream
DataInputStream inn = new DataInputStream(fstr);
BufferedReader brr = new BufferedReader(new InputStreamReader(inn));
String readstr;
java.sql.DatabaseMetaData dmd = conn.getMetaData();
while ((readstr = brr.readLine()) != null) //DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
//while(readstr!=null)
{
ResultSet rs = dmd.getTables(null, "DB", "example11199", null);
//set not null column
if (String.valueOf(readstr).contains("NO")) {
readstr = readstr.replaceAll("NO", "not null");
} else if (String.valueOf(readstr).contains("YES")) {
readstr = readstr.replaceAll("YES", "");
}
if (String.valueOf(readstr).contains("PRIMARY")) {
readstr = readstr.replaceFirst("PRIMARY", "primary key");
}
System.out.println("replace string " + readstr);
int k = 1;
if (!rs.next()) {
stmt.executeUpdate("CREATE TABLE " + tname + "(" + readstr + ")");
} else {
//System.out.println(readstr);
stmt.executeUpdate("ALTER TABLE " + tname + " ADD(" + readstr + ")");
System.out.println("altered");
}
}
brr.close();
inn.close();
} catch (Exception e) {
}
}
}
EDITED, Now all contents of text file gets printed but it gives null here at last : System.out.println("replace string " + readstr); so i am unalble to create table with null value.
Thank You.
You are re-creating the table you read one line. I assume this only works once, so it is only reading the first line.
You appear to have a jumble of text passing and altering a table so that only the file line is read before you attempt to create the table. I suspect you want to read the whole file before you attempt to alter/create the table.
BTW Having formatting all over the place is likely to make checking your code much harder. I suggest you use the formatter in your IDE and you should be able to see how your code will loop.
while ((readstr = brr.readLine()) != null) //DatabaseMetaData dmd = (DatabaseMetaData) conn.getMetaData();
//while(readstr!=null)
{
ResultSet rs = dmd.getTables(null, "DB", "example11199", null);
//set not null column
if (String.valueOf(readstr).contains("NO")) {
readstr = readstr.replaceAll("NO", "not null");
} else if (String.valueOf(readstr).contains("YES")) {
readstr = readstr.replaceAll("YES", "");
}else if (String.valueOf(readstr).contains("PRIMARY")) {
readstr = readstr.replaceFirst("PRIMARY", "primary key");
}
System.out.println("replace string " + readstr);
Try to fix the last if statement Check it again and it will Work.
I'm using random access files to write a raf using an arrayList store. I do not know if it can be done, but I'm giving it a try because it is the best solution for me to create this application.
Here is the run-time error that I am getting:
Exception in thread "main" java.io.EOFException
at java.io.RandomAccessFile.readChar(Unknown Source)
at Student.read(Student.java:93)
at MainApp.start(MainApp.java:60)
at MainApp.main(MainApp.java:17)
And here is my code:
MainApp
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
public class MainApp
{
public static void main(String[] args) throws Exception
{
new MainApp().start();
}
public void start()throws Exception
{
StudentStore details = new StudentStore();
//Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
//details.print();
RandomAccessFile raf = new RandomAccessFile("ContactDetails.txt", "rw");
Student a = new Student("Becky O'Brien", "DKIT26", "0876126944", "bexo#hotmail.com");
Student b = new Student("Fabio Borini", "DKIT28", "0876136944", "fabioborini#gmail.com");
Student c = new Student("Gaston Ramirez", "DKIT29", "0419834501", "gramirez#webmail.com");
Student d = new Student("Luis Suarez", "DKIT7", "0868989878", "luissuarez#yahoo.com");
Student e = new Student("Andy Carroll", "DKIT9", "0853456788", "carroll123#hotmail.com");
details.add(a);
details.add(b);
details.add(c);
details.add(d);
details.add(e);
for (int i = 0; i < details.size(); i++)
{
//a.setStudentName(a[i]);
//a.setLastName(lnames[i]);
// a.setAddress(addresses[i]);
// a.setAge(ages[i]);
// a.setSalary(salaries[i]);
a.write(raf);
}
raf = new RandomAccessFile("employee.dat", "rw");
// er = new Student();
int numRecords = (int) raf.length() / details.size();
for (int i = 0; i < numRecords; i++) {
a.read(raf);
System.out.print(a.getStudentName() + " ");
System.out.print(a.getStudentId() + " ");
System.out.print(a.getStudentEmail() + " ");
System.out.print(a.getStudentTelephoneNumber() + " ");
}
raf.seek(0);
for (int i = 0; i < numRecords; i++)
{
a.read(raf);
raf.seek(raf.getFilePointer() - details.size());
a.write(raf);
raf.seek(raf.getFilePointer() - details.size());
a.read(raf);
}
System.out.print(a.getStudentName() + " ");
System.out.print(a.getStudentId() + " ");
System.out.print(a.getStudentEmail() + " ");
System.out.print(a.getStudentTelephoneNumber() + " ");
}
}
Student
import java.io.IOException;
import java.io.RandomAccessFile;
public class Student
{
//---------------------------------------------------------------------------
// Class Variables.
//---------------------------------------------------------------------------
private String studentName;
private String studentId;
private String studentTelephoneNumber;
private String studentEmail;
//---------------------------------------------------------------------------
// Constructor.
//---------------------------------------------------------------------------
public Student(String studentName, String studentId,String studentTelephoneNumber, String studentEmail)
{
this.studentName = studentName;
this.studentId = studentId;
this.studentTelephoneNumber = studentTelephoneNumber;
this.studentEmail = studentEmail;
}
//---------------------------------------------------------------------------
// Getters.
//---------------------------------------------------------------------------
public String getStudentName()
{
return studentName;
}
public String getStudentId()
{
return studentId;
}
public String getStudentTelephoneNumber()
{
return studentTelephoneNumber;
}
public String getStudentEmail()
{
return studentEmail;
}
//---------------------------------------------------------------------------
// Setters.
//---------------------------------------------------------------------------
public void setStudentName(String studentName)
{
this.studentName = studentName;
}
public void setStudentId(String studentId)
{
this.studentId = studentId;
}
public void setStudentTelephoneNumber(String studentTelephoneNumber)
{
this.studentTelephoneNumber = studentTelephoneNumber;
}
public void setStudentEmail(String studentEmail)
{
this.studentEmail = studentEmail;
}
//---------------------------------------------------------------------------
// toString.
//---------------------------------------------------------------------------
public String toString()
{
return "---------------------------Student--------------------------- " +
"\nStudent Name:" + studentName +
"\nStudent Id:"+ studentId +
"\nStudent Telephone Number:"+ studentTelephoneNumber +
"\nStudent Email:" + studentEmail;
}
void read(RandomAccessFile raf) throws IOException
{
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentName = new String(temp);
temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentId = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentEmail = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
studentTelephoneNumber = new String(temp);
temp = new char[30];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
}
void write(RandomAccessFile raf) throws IOException
{
StringBuffer sb;
if (studentName != null)
sb = new StringBuffer(studentName);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (studentId != null)
sb = new StringBuffer(studentId);
else
sb = new StringBuffer();
sb.setLength(15);
raf.writeChars(sb.toString());
if (studentEmail != null)
sb = new StringBuffer(studentEmail);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
if (studentTelephoneNumber != null)
sb = new StringBuffer(studentTelephoneNumber);
else
sb = new StringBuffer();
sb.setLength(30);
raf.writeChars(sb.toString());
}
}
You are reading beyond the end of the file. Reading data that isn't there.
The basic problem is that you are reading more data than you are writing.
You are reading 30 char at the end of each record which you didn't write. Given you discard them it appears you don't need to be doing this. I would delete the code which reads after studentTelephoneNumber
If load just one detail do you get the problem? I think your problem is that you are reading off the end of the file. Your read function which reads 15/30 characters seem dangerous because you may not have written that much. Why not read until you get a comma or some other separator? (eg tab)
It's this sort of thing that looks dangerous
char[] temp = new char[15];
for (int i = 0; i < temp.length; i++)
temp[i] = raf.readChar();
Where does the 15 come from?
Try and break it down with just one detail and bulid up from there. You should find the error. I would personally read until you find a particular separator.