Java Swing and Excel [duplicate] - java

This question already has answers here:
How to read and write excel file
(22 answers)
Closed 5 years ago.
I am trying to write the data from table format to to Excel sheet,during this date is shown as "#######" in excel.But while i increasing the cell size the date is visible correctly.So i want to increase the width size of the excel file from the code itself.Is anyone can help me ?The code is below`
JButton btnExport = new JButton("Export To Excel");
btnExport.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e1) {
btnExport.setMnemonic(KeyEvent.VK_X);
btnExport.addActionListener(new AksyonListener());
}
public void toExcel(JTable table1, File file) {
try {
System.out.println("Success");
FileWriter excel = new FileWriter(file);
// DefaultTableModel model = new DefaultTableModel();
// table.setModel(model);
// model.insertRow(table.getRowCount(), new Object[]{0});
for (int i = 0; i < table.getColumnCount(); i++) {
excel.write(table.getColumnName(i) + "\t");
System.out.println(table.getColumnName(i));
}
/* int d,f;
System.out.println("d: "+table.getRowCount());
System.out.println("f: "+table.getColumnCount());*/
excel.write("\n");
for (int i = 1; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
excel.write(table.getValueAt(i, j) + "\t");
System.out.println(table.getValueAt(i, j));
}
excel.write("\n");
}
excel.close();
} catch (IOException e) {
System.out.println(e);
}
}
class AksyonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnExport) {
JFileChooser fc = new JFileChooser();
int option = fc.showSaveDialog(TableSortFilter.this);
if (option == JFileChooser.APPROVE_OPTION) {
String filename = fc.getSelectedFile().getName();
String path = fc.getSelectedFile().getParentFile().getPath();
int len = filename.length();
String ext = "";
String file = "";
if (len > 4) {
ext = filename.substring(len - 4, len);
}
if (ext.equals(".xls")) {
file = path + "\\" + filename;
} else {
file = path + "\\" + filename + ".xls";
}
toExcel(table, new File(file));
}
}
}
}
});

Try to use apache poi to export and create excel
https://poi.apache.org/

Related

Blank row after header

I am writing existing excel by merging many excel files, after generating of final excel file blank row is adding up after headers.
Below is my code which reads data from multiple files and write to particular blank file which have pivot formulas set.
I tried even by
1. Setting createRow(0) , then started filling data from next row.
2. Tried of maintaining int counter, but still didn't work
3. Tried incrementing getLastRowNum() count, but no use
public class DCSReadImpl implements ReadBehavior {
Logger log = Logger.getLogger(DCSReadImpl.class.getName());
#SuppressWarnings("resource")
#Override
public Sheet readReport(Workbook workbook,Map<String,String> masterMap, Properties properties) {
//int firstRow = 0;
int outRowCounter = 0;
String fileToMove= "";
boolean headers = true;
Row outputRow = null;
Sheet outputSheet = null;
Workbook wb = new XSSFWorkbook();
try {
outputSheet = wb.createSheet("Data");
log.info("**** Set headers start"); // this used to be different method
int cellNo = 0;
outputRow = outputSheet.createRow(0);
for(String headerName : ReportConstants.DCS_OUTPUT_HEADER){
outputRow.createCell(cellNo).setCellValue(headerName);
cellNo++;
}
//outRowCounter++;
log.info("**** Set headers completed");
log.info("Read input file(s) for DCS report");
log.info("Input File Path : " + properties.getProperty(ReportConstants.DCS_INPUT_PATH));
File inputDir = new File(properties.getProperty(ReportConstants.DCS_INPUT_PATH));
File[] dirListing = inputDir.listFiles();
if (0 == dirListing.length) {
throw new Exception(properties.getProperty(ReportConstants.DCS_INPUT_PATH) + " is empty");
}
for (File file : dirListing) {
log.info("Processing : " + file.getName());
fileToMove = file.getName();
XSSFWorkbook inputWorkbook = null;
try {
inputWorkbook = new XSSFWorkbook(new FileInputStream(file));
} catch (Exception e) {
throw new Exception("File is already open, please close the file");
}
XSSFSheet inputsheet = inputWorkbook.getSheet("Sheet1");
Iterator<Row> rowItr = inputsheet.iterator();
int headItr = 0;
//log.info("Validating headers : " + file.getName());
while (rowItr.hasNext()) {
Row irow = rowItr.next();
Iterator<Cell> cellItr = irow.cellIterator();
int cellIntItr = 0;
String key = "";
int rowN = outputSheet.getLastRowNum() + 1;
outputRow = outputSheet.createRow(rowN);
Cell outCell = null;
while (cellItr.hasNext()) {
Cell inputCell = cellItr.next();
if (0 == inputCell.getRowIndex()) {
if (!FileUtility.checkHeaders(headItr, inputCell.getStringCellValue().trim(),
ReportConstants.DCS_INPUT_HEADER)) {
throw new Exception("Incorrect header(s) present in Input File, Expected : "
+ ReportConstants.DCS_INPUT_HEADER[headItr]);
}
headItr++;
} else {
//outCell = outputRow.createCell(cellIntItr);
if (0 == inputCell.getColumnIndex()) {
key = inputCell.getStringCellValue().trim();
} else if (2 == inputCell.getColumnIndex()) {
key = key + ReportConstants.DEL + inputCell.getStringCellValue().trim();
}
if (7 == cellIntItr){
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(getValue(masterMap, key, 0));
cellIntItr++;
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(getValue(masterMap, key, 1));
cellIntItr++;
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(getValue(masterMap, key, 2));
cellIntItr++;
}
// Check the cell type and format accordingly
switch (inputCell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(inputCell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
outCell = outputRow.createCell(cellIntItr);
outCell.setCellValue(inputCell.getStringCellValue().trim());
break;
}
cellIntItr++;
}
}
//outRowCounter ++ ;
}
if(!fileToMove.isEmpty()){
FileUtility.checkDestinationDir(""+properties.get(ReportConstants.DCS_ARCHIVE_PATH));
FileUtility.moveFile(properties.get(ReportConstants.DCS_INPUT_PATH) + fileToMove,
properties.get(ReportConstants.DCS_ARCHIVE_PATH)+fileToMove+FileUtility.getPattern());
}
}
} catch (Exception e) {
log.error("Exception occured : ", e);
}
FileOutputStream outputStream;
try {
outputStream = new FileOutputStream("D:\\DCS\\Output\\Krsna_"+FileUtility.getPattern()+".xlsx");
wb.write(outputStream);
} catch (Exception e) {
e.printStackTrace();
}
return outputSheet;
}
private String getValue(Map<String, String> masterMap, String cellKey, int index) {
String value = masterMap.get(cellKey);
if (null != value) {
String cellValue[] = value.split("\\" + ReportConstants.DEL);
return cellValue[index];
} else {
return "";
}
}
}
There should not be blank row after header row. That is in between of 0th row and 1st row (hope my understanding is correct on row indexing). I know this is very basic question :-(

how to read xls file into jtable

Im having trouble with importing XLS data to jtable.
My program reads only the last row from XLS.
Here is my code:
JButton btnImportExcelFiles = new JButton("EXCEL FILES");
btnImportExcelFiles.setIcon(new ImageIcon(racunariAplikacija.class.getResource("/image/Excel-icon.png")));
btnImportExcelFiles.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
FileFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
// here is my file chooser
JFileChooser jf = new JFileChooser();
jf.addChoosableFileFilter(filter);
int rezultat = jf.showOpenDialog(null);
if(rezultat == JFileChooser.APPROVE_OPTION)
{
String excelPath = jf.getSelectedFile().getAbsolutePath();
ArrayList<Stavka>lista = new ArrayList<>();
Stavka stavka = new Stavka();
File f = new File(excelPath);
Workbook wb = null;
try {
wb = Workbook.getWorkbook(f);
}
catch (BiffException e) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
// this is where i call for nested forloop
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
System.out.println("redovi" + row + "kolone" + col);
for (int i = 0; i < 18; i++) {
for (int j = 0; j < col; j++) {
Cell c = s.getCell(j,i);
if(j==0) {stavka.setStavkaID(Integer.parseInt(c.getContents().toString()));}
else if(j==1) {}
else if(j==2) {stavka.setSifraKomponente(c.getContents().toString());}
else if(j==3) {stavka.setOpis(c.getContents().toString());}
else if(j==4) {stavka.setVrednost(c.getContents().toString());}
else if(j==5) {stavka.setKuciste(c.getContents().toString());}
else if(j==6) {stavka.setSektor(c.getContents().toString());}
else if(j==7) {stavka.setRack(c.getContents().toString());}
else if(j==8) {stavka.setProizvodjac(c.getContents().toString());}
else if(j==9) {stavka.setKolicina(Integer.parseInt(c.getContents().toString()));}
//System.out.println(c.getContents());
}
// this is my tableModel
lista.add(stavka);
TabelaStavka stavka1 = new TabelaStavka(lista);
tblAzuriranjeMagacina.setModel(stavka1);
}
}
}
}
How can this be fixed?
I believe the error exists because you must create a new Stavka object for each line in your XLS, and then add it to 'lista'. Finally, I believe you also want to set the model (TabelaStavka) outside these for loops.
I don't have a full Java environment installed here, so forgive me if there is any syntax error below. The most important thing is that you understand what are the fixes you have to do in your code.
Also, never underestimate code formatting, you should consider using a better IDE, which helps out better formatting your source code.
JButton btnImportExcelFiles = new JButton("EXCEL FILES");
btnImportExcelFiles.setIcon(new ImageIcon(racunariAplikacija.class.getResource("/image/Excel-icon.png")));
btnImportExcelFiles.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent arg0)
{
FileFilter filter = new FileNameExtensionFilter("Excel Files", "xls");
// here is my file chooser
JFileChooser jf = new JFileChooser();
jf.addChoosableFileFilter(filter);
int rezultat = jf.showOpenDialog(null);
if(rezultat == JFileChooser.APPROVE_OPTION)
{
String excelPath = jf.getSelectedFile().getAbsolutePath();
ArrayList<Stavka>lista = new ArrayList<>();
File f = new File(excelPath);
Workbook wb = null;
try
{
wb = Workbook.getWorkbook(f);
}
catch (BiffException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
// this is where i call for nested forloop
Sheet s = wb.getSheet(0);
int row = s.getRows();
int col = s.getColumns();
System.out.println("redovi" + row + "kolone" + col);
for (int i = 0; i < 18; i++)
{
Stavka stavka = new Stavka(); // new instance <<<<<<<<
for (int j = 0; j < col; j++)
{
Cell c = s.getCell(j,i);
if(j==0) {stavka.setStavkaID(Integer.parseInt(c.getContents().toString()));}
else if(j==1) {}
else if(j==2) {stavka.setSifraKomponente(c.getContents().toString());}
else if(j==3) {stavka.setOpis(c.getContents().toString());}
else if(j==4) {stavka.setVrednost(c.getContents().toString());}
else if(j==5) {stavka.setKuciste(c.getContents().toString());}
else if(j==6) {stavka.setSektor(c.getContents().toString());}
else if(j==7) {stavka.setRack(c.getContents().toString());}
else if(j==8) {stavka.setProizvodjac(c.getContents().toString());}
else if(j==9) {stavka.setKolicina(Integer.parseInt(c.getContents().toString()));}
}
lista.add(stavka); // inside second for loop <<<<<<<<
}
// outside the second for loop <<<<<<<<<<<<<<<<<<<<<<<<<<
// this is my tableModel
TabelaStavka stavka1 = new TabelaStavka(lista);
tblAzuriranjeMagacina.setModel(stavka1);
}
}
}

How to convert multipage PDF to multipage TIFF

I am using Ghost4j to convert multipage PDFs to multipage TIFF images. I haven't found an example of how this is done.
Using below code I'm able to convert the multipage PDF to images but how do I create a single multipage TIFF image out of it?
PDFDocument lDocument = new PDFDocument();
lDocument.load(filePath);
// create renderer
SimpleRenderer lRenderer = new SimpleRenderer();
// set resolution (in DPI)
lRenderer.setResolution(300);
// render as images
List<Image> lImages = lRenderer.render(lDocument);
Iterator<Image> lImageIterator = lImages.iterator();
//how to convert the images to a single TIFF image?
While this is not exactly what you are doing I did something similar. I combined multiple images in one directory into a tiff file with separate pages. Take a look at this code and see if you can pick out what you need. Also you will need external jars/libraries for this to work they can be downloaded just google them. I hope this helps you.
public class CombineImages {
private static String directory = null;
private static String combinedImageLocation = null;
private static DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
private static int folderCount = 0;
private static int totalFolderCount = 0;
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(System.in);
System.out.println("Please enter the directory path that contains the images: ");
directory = scanner.nextLine(); //initialize directory
System.out.println("Please enter a location for the new combined images to be placed: ");
combinedImageLocation = scanner.nextLine(); //initialize directory
if(!(combinedImageLocation.charAt((combinedImageLocation.length() - 1)) == '\\'))
{
combinedImageLocation += "\\";
}
if(!(directory.charAt((directory.length() - 1)) == '\\'))
{
directory += "\\";
}
scanner.close();
//directory = "C:\\Users\\sorensenb\\Desktop\\CombinePhotos\\";
//combinedImageLocation = "C:\\Users\\sorensenb\\Desktop\\NewImages\\";
File filesDirectory;
filesDirectory = new File(directory);
File[] files; //holds files in given directory
if(filesDirectory.exists())
{
files = filesDirectory.listFiles();
totalFolderCount = files.length;
folderCount = 0;
if(files != null && (files.length > 0))
{
System.out.println("Start Combining Files...");
System.out.println("Start Time: " + dateFormat.format(new Date()));
combineImages(files);
System.out.println("Finished Combining Files.");
System.out.println("Finish Time: " + dateFormat.format(new Date()));
}
}
else
{
System.out.println("Directory does not exist!");
System.exit(1);
}
}
public static void combineImages(File[] files)
{
int fileCounter = 1;
ArrayList<String> allFiles = new ArrayList<String>();
String folderBase = "";
String parentFolder = "";
String currentFileName = "";
String previousFileName = "";
File previousFile = null;
int counter = 0;
for(File file:files)
{
if(file.isDirectory())
{
folderCount++;
System.out.println("Folder " + folderCount + " out of " + totalFolderCount + " folders.");
combineImages(file.listFiles());
}
else
{
try {
folderBase = file.getParentFile().getCanonicalPath();
parentFolder = file.getParentFile().getName();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if(counter == 0)
{
allFiles.add(file.getName().substring(0, file.getName().indexOf('.')));
}
else
{
currentFileName = file.getName();
previousFileName = previousFile.getName();
currentFileName = currentFileName.substring(0, currentFileName.indexOf('.'));
previousFileName = previousFileName.substring(0, previousFileName.indexOf('.'));
if(!currentFileName.equalsIgnoreCase(previousFileName))
{
allFiles.add(currentFileName);
}
}
}
previousFile = file;
counter++;
}
System.out.println("Total Files to be Combined: " + allFiles.size());
for(String currentFile:allFiles)
{
System.out.println("File " + fileCounter + " out of " + allFiles.size() + " CurrentFile: " + currentFile);
try {
createNewImage(currentFile, files, folderBase, parentFolder);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
fileCounter++;
}
}
***public static void createNewImage(String currentFile, File[] files, String folderBase, String parentFolder) throws IOException
{
//BufferedImage image;
int totalHeight = 0;
int maxWidth = 0;
int currentHeight = 0;
ArrayList<String> allFiles = new ArrayList<String>();
for(File file:files)
{
if((file.getName().substring(0, file.getName().indexOf('.'))).equalsIgnoreCase(currentFile))
{
allFiles.add(file.getName());
}
}
allFiles = sortFiles(allFiles);
BufferedImage image[] = new BufferedImage[allFiles.size()];
SeekableStream ss = null;
PlanarImage op = null;
for (int i = 0; i < allFiles.size(); i++) {
ss = new FileSeekableStream(folderBase + "\\" + allFiles.get(i));
ImageDecoder decoder = ImageCodec.createImageDecoder("tiff", ss, null);
op = new NullOpImage(decoder.decodeAsRenderedImage(0),
null, null, OpImage.OP_IO_BOUND);
image[i] = op.getAsBufferedImage();
}
op.dispose();
ss.close();
/*BufferedImage convertImage;
for(int i = 0; i < image.length; i++)
{
convertImage = new BufferedImage(image[i].getWidth(),image[i].getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics g = convertImage.getGraphics();
g.drawImage(convertImage, 0, 0, null);
g.dispose();
image[i] = convertImage;
}*/
File folderExists = new File(combinedImageLocation);
if(!folderExists.exists())
{
folderExists.mkdirs();
}
TIFFEncodeParam params = new TIFFEncodeParam();
params.setCompression(TIFFEncodeParam.COMPRESSION_GROUP3_1D);
int changeName = 1;
String tempCurrentFile = currentFile;
while((new File(combinedImageLocation + tempCurrentFile + "Combined.tif").exists()))
{
tempCurrentFile = currentFile;
tempCurrentFile += ("(" + changeName + ")");
changeName++;
}
currentFile = tempCurrentFile;
OutputStream out = new FileOutputStream(combinedImageLocation + currentFile + "Combined" + ".tif");
ImageEncoder encoder = ImageCodec.createImageEncoder("tiff", out, params);
Vector vector = new Vector();
for (int i = 1; i < allFiles.size(); i++) {
vector.add(image[i]);
}
params.setExtraImages(vector.iterator());
encoder.encode(image[0]);
for(int i = 0; i < image.length; i++)
{
image[i].flush();
}
out.close();
System.gc();
/*for(String file:allFiles)
{
image = ImageIO.read(new File(folderBase, file));
int w = image.getWidth();
int h = image.getHeight();
totalHeight += h;
if(w > maxWidth)
{
maxWidth = w;
}
image.flush();
}
BufferedImage combined = new BufferedImage((maxWidth), (totalHeight), BufferedImage.TYPE_BYTE_GRAY);
for(String file:allFiles)
{
Graphics g = combined.getGraphics();
image = ImageIO.read(new File(folderBase, file));
int h = image.getHeight();
g.drawImage(image, 0, currentHeight, null);
currentHeight += h;
image.flush();
g.dispose();
}
File folderExists = new File(combinedImageLocation + parentFolder + "\\");
if(!folderExists.exists())
{
folderExists.mkdirs();
}
ImageIO.write(combined, "TIFF", new File(combinedImageLocation, (parentFolder + "\\" + currentFile + "Combined.tif")));
combined.flush();
System.gc();*/
}***
public static ArrayList<String> sortFiles(ArrayList<String> allFiles)
{
ArrayList<String> sortedFiles = new ArrayList<String>();
ArrayList<String> numbers = new ArrayList<String>();
ArrayList<String> letters = new ArrayList<String>();
for(String currentFile:allFiles)
{
try
{
Integer.parseInt(currentFile.substring((currentFile.indexOf('.') + 1)));
numbers.add(currentFile);
}catch(Exception e)
{
letters.add(currentFile);
}
}
//String[] numbersArray = new String[numbers.size()];
//String[] lettersArray = new String[letters.size()];
for(int i = 0; i < numbers.size(); i++)
{
sortedFiles.add(numbers.get(i));
}
for(int i = 0; i < letters.size(); i++)
{
sortedFiles.add(letters.get(i));
}
return sortedFiles;
}
}

reading desired data from file but saving the whole file data

I have made a GUI using swing, i read data from a text file to the jtable,
the text file has 6 columns and 5 rows,the 3 row has values 0,0.0,0,0,0,0.so i want to display
values in the JTable till it encounters 0.but to save the full text file while saving which means values of 5 rows.here is my code:
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
public class Bb extends JFrame
{
private JTable table;
private DefaultTableModel model;
#SuppressWarnings("unchecked")
public Bb()
{
String aLine ;
Vector columnNames = new Vector();
Vector data = new Vector();
try
{
FileInputStream fin = new FileInputStream("Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
while( st1.hasMoreTokens())
{
columnNames.addElement(st1.nextToken());
}
while ((aLine = br.readLine()) != null )
{
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while(st2.hasMoreTokens())
{
row.addElement(st2.nextToken());
}
data.addElement( row );
}
br.close();
}
catch (Exception e)
{
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
JButton button2 = new JButton( "SAVE TABLE" );
buttonPanel.add( button2 );
button2.addActionListener( new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
if ( table.isEditing() )
{
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuffer Con = new StringBuffer();
for (int i = 0; i < table.getRowCount(); i++)
{
for (int j = 0; j < table.getColumnCount(); j++)
{
Object Value = table.getValueAt(i, j);
Con.append(" ");
Con.append(Value);
}
Con.append("\r\n");
}
FileWriter fileWriter = new FileWriter(new File("cc.txt"));
fileWriter.write(Con.toString());
fileWriter.flush();
fileWriter.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public static void main(String[] args)
{
Bb frame = new Bb();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
and the text file:
1 2 6 0.002 0.00 2
2 5 5 0.005 0.02 4
0 0 0 0.000 0.00 0
4 8 9 0.089 0.88 7
5 5 4 0.654 0.87 9
I was able to understand what you want
For first part that you just wanted to show your data in your JTable till you encounter 0
code:
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0")) {
break;
}
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
Explanation: when you read each line, split it, so if the first element of each splitted line is zero, you come out of the loop and do not show any other values inside the loop.
For saving all your data from first file to second file, you should copy them from first file to second file because your JTable will not have enough info to help your purpose in this matter.
Note: I do not understand why you want to do this but you can accomplish that in following way
Code:
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
String st = "";
FileInputStream fin = new FileInputStream("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
Scanner input = new Scanner(fin).useDelimiter("\\A");
while (input.hasNext()) {
st = input.next();
System.out.println("st is " + st);
}
FileWriter fileWriter = new FileWriter(new File("C:\\Users\\J Urguby"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"));
fileWriter.write(st);
fileWriter.flush();
fileWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
Explanation: you read the whole file with Scanner trick and write it down into a second file.
Source: https://weblogs.java.net/blog/pat/archive/2004/10/stupid_scanner.html
Based on what the OP requested
Code:
public Bb() {
String aLine;
Vector columnNames = new Vector();
Vector data = new Vector();
boolean found = false;
StringBuilder temp = new StringBuilder();
/*Using try catch block with resources Java 7
Read about it
*/
try (FileInputStream fin = new FileInputStream("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\Bbb.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fin))) {
StringTokenizer st1 = new StringTokenizer(br.readLine(), " ");
//the first line of the txt file fill colum names
while (st1.hasMoreTokens()) {
String s = st1.nextToken();
columnNames.addElement(s);
}
while ((aLine = br.readLine()) != null) {
String[] sp = aLine.split(" ");
if (sp[0].equals("0") && !found) {
found = true;
} else if (found) {
temp.append(aLine).append("\r\n");
} else if (!sp[0].equals("0") && !found) {
StringTokenizer st2 = new StringTokenizer(aLine, " ");
Vector row = new Vector();
while (st2.hasMoreTokens()) {
String s = st2.nextToken();
row.addElement(s);
}
data.addElement(row);
}
}
} catch (IOException e) {
e.printStackTrace();
}
model = new DefaultTableModel(data, columnNames);
table = new JTable(model);
JScrollPane scrollPane = new JScrollPane(table);
getContentPane().add(scrollPane);
JPanel buttonPanel = new JPanel();
getContentPane().add(buttonPanel, BorderLayout.SOUTH);
JButton button2 = new JButton("SAVE TABLE");
buttonPanel.add(button2);
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (table.isEditing()) {
int row = table.getEditingRow();
int col = table.getEditingColumn();
table.getCellEditor(row, col).stopCellEditing();
}
int rows = table.getRowCount();
int columns = table.getColumnCount();
try {
StringBuilder con = new StringBuilder();
for (int i = 0; i < table.getRowCount(); i++) {
for (int j = 0; j < table.getColumnCount(); j++) {
Object Value = table.getValueAt(i, j);
con.append(" ");
con.append(Value);
}
con.append("\r\n");
}
try (FileWriter fileWriter = new FileWriter(new File("C:\\Users\\8888"
+ "\\Documents\\NetBeansProjects\\Bb\\src\\bb\\cc.txt"))) {
fileWriter.write(con.append(temp).toString());
fileWriter.flush();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
My code just works if you have row includes zeros. if you want to make it better to cover up all conditions, I am sure you can follow my plan.
Sample to get rid of all zeros like
1 1 1
0 0 0
0 0 0
1 1 1
Code:
String s = "xxxooooooxxx";
String[] sp = s.split("");
boolean xFlag = false;
for (int i = 0; i < sp.length; i++) {
if (sp[i].equals("x") && !xFlag) {
System.out.print("x");
} else if (sp[i].equals("o")) {
xFlag = true;
} else if (sp[i].equals("x") && xFlag) {
System.out.print("X");
}
}
output:
xxxXXX

Writing 2d array into file that needs to look like array

I have the following code that creates and writes to the file but it writes everything out in one solid line.
Example: 11111111111111111111111111
I need it look like the following(space in between every number):
1 1 1 1 1 1
1 1 1 1 1 1
1 1 1 1 1 1
Here is my code:
public void saveFile()
{
String save = "Testing";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]));
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
}
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
This is because you are not putting space between them.
bw.write(String.valueOf(gameArray[row][col]));
bw.write(" ");
and at the end of inner loop, again,
bw.write("\n");
write bw.write("\n") at the end of your inner loop.
Just like :
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]));
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
bw.write("\n")
}
This should work for you:
public void saveFile()
{
String save = "Testing";
JFileChooser fc = new JFileChooser();
int returnVal = fc.showSaveDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
try {
FileWriter bw = new FileWriter(fc.getSelectedFile()+".txt");
for(int row = 0; row < gameArray.length; row++)
{
for(int col =0; col < gameArray[row].length; col++)
{
bw.write(String.valueOf(gameArray[row][col]);
if ((col+1)!=gameArray[row].length)
bw.write(" ");
System.out.println(gameArray[row][col] + " ");
System.out.println();
}
bw.write(System.getProperty("line.seperator"));
}
bw.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

Categories

Resources