How do I add data from a file to a JTable? - java

Here is my method so far:
public void readfile(JTable table) {
try{
BufferedReader in = new BufferedReader( new FileReader("out.txt"));
for(int i = 0; i<10; i++) {
for(int j = 0; j<5; j++) {
table.setValueAt(in.readLine(), i, j);
}
}
in.close();
}catch (Exception e) {
System.err.println("error: " + e.getMessage());
}
}
Here are the contents of out.txt:
test1
test2
test3
test4
test5
Where I run the program and attempt to load the file to the table, nothing happens. I also get an output that says the following:
error: 0 >= 0
Help me please?

I would narrow your problem down to a smaller problem, solve this smaller problem, and then widen it until you have want you want.
Think of the contents of a File as a big blob of text.
Think of the table as a Vector of Vectors.
Smaller problem: How do I convert a big blob of text into a Vector of Vectors? You need to be able to sove this problem first before tackling File I/O or DefaultTableModels.

Related

Java Strings not printing above length 4094

So I've got a program that generates large binary sequences, and if the string length goes above 4094 it doesn't print. Here's a code snippet the highlights the problem:
private static void ALStringTest() {
String al = "1";
for (int i = 0; i < 5000; i++) {
al += "1";
System.out.println(al.length());
System.out.println(al);
System.out.println(al.isEmpty());
}
}
What's interesting is the length continues to increase, and the boolean value stays false, but I'm unable to see the strings of length 4095 and above.
It's also not a printing error, as I've attempted to write the strings to xml and they don't appear either, all I get is spaces equal to the strings length.
Edit:
I've tried printing a file using this snippet and I have the same problem:
private static void ALStringTest() throws IOException {
File fout = new File("out.txt");
FileOutputStream fos = new FileOutputStream(fout);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
String al = "1";
for (int i = 0; i < 5000; i++) {
al += "1";
bw.write(al);
bw.newLine();
System.out.println(al.length());
System.out.println(al);
System.out.println(al.isEmpty());
}
bw.close();
}
However, people have confirmed this works on external machines (thanks) (as well as on my own using javac, I'm lead to believe this may be Eclipse specific.
Anyone know why Eclipse might be doing this?
the boolean will stay false as hashcode of al is some value and that of "" is 0, == checks for reference.
So it turns out it was an IDE issue:
Simply copying it to a text editor revealed the strings. I'll update when I find the offending option.
The possible reason of this maybe the defect of console which is rapidly printing output results. So that maybe it's only happening in console output. I've tested those each and the result was sometime it prints false only more than 6 times or sometime it prints only length That shouldn't be happened as scenario. But everything works fine when we use thread and make it sleep even 1 millisecond. The output is fine enough as codes,
class ThreadTest extends Thread {
public ThreadTest() {
super();
}
public void run() {
String al = "1";
for (int i = 0; i < 5000; i++) {
try {
sleep(1);
al += "1";
System.out.println(al.length());
System.out.println(al);
System.out.println(al.equals(""));
} catch (InterruptedException e) {
}
}
}
}
Call this in main method
new ThreadTest().start();

Loading partial sudoku text file into 2D array

I am making a Sudoku game and I have an issue with opening a saved Sudoku file. Let's say I am doing the puzzle, and want to come back to it later, I save the partially completed puzzle to a file, which works. When I go to open it, it does not work.
Here is the code for save (both variables ROWS and COLUMNS are equal to 9):
private void savePuzzle() throws IOException {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showDialog(this, "Save");
BufferedWriter saveFile = null;
File file;
// If the user has canceled, no need to continue
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
file = fileChooser.getSelectedFile();
saveFile = new BufferedWriter(new FileWriter(file));
for (int r = 0; r < ROWS; r++) {
for (int c = 0; c < COLUMNS; c++) {
saveFile.write(inputBoxes[r][c].getText());
if (c < ROWS - 1) {
saveFile.write(",");
}
}
saveFile.write("\n");
}
saveFile.close();
}
Here is the action button for save:
saveAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
// call method to save puzzle by writing its contents to an external save file
savePuzzle();
} catch (IOException ex) {
System.out.println(ex.toString());
}
}
});
Here is the code for open:
private void openPuzzle() throws FileNotFoundException, IllegalArgumentException {
JFileChooser fileChooser = new JFileChooser();
int returnVal = fileChooser.showDialog(this, "Open");
File file = fileChooser.getSelectedFile();
Scanner readFile = new Scanner(file);
// If the user has canceled, no need to continue with open process
if (returnVal != JFileChooser.APPROVE_OPTION) {
return;
}
// Row
int r = 0;
// Update squares with data from file
while (readFile.hasNextLine()) {
String[] splitLine = readFile.nextLine().split(",");
// Verify the length of the row
if (splitLine.length != 9) {
throw new IllegalArgumentException(String.format("Row length(%d) not correct in %s at row %d",
splitLine.length, file, r));
}
for (int c = 0; c < 9; c++) {
// Verify each item in row
if (splitLine[c].length() != 1 || !(Character.isDigit(splitLine[c].charAt(0)))) {
throw new IllegalArgumentException(String.format("Invalid token %s in %s at row %d col %d",
splitLine[c], file, r, c));
}
// Update square
inputBoxes[r][c].setText(splitLine[c]);
}
// Move to next row
r++;
}
}
And the open action button:
openAction.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
try {
// call method so that user can open their saved puzzle and populate the grid with its contents
openPuzzle();
} catch (FileNotFoundException ex) {
System.out.println(ex.toString());
} catch (IllegalArgumentException ex) {
System.out.println(ex.toString());
}
}
});
I know that the open code is finding empty values in the saved text file if it is a partially completed puzzle, and it is returning those catch statements, but I have no clue how to get it to just keep reading each element on the line (whether it's a number or empty space), and just return what's in the text file to the GUI grid (populate the grid with the corresponding numbers).
The errors I'm getting are either the "Row length %d..." error or the "Invalid token %s..." error. It loads nothing back into the grid when I select the file from the Open function. That's where I'm lost. If the puzzle is complete, and it is saved, then it can be open, because the external text file that contains the puzzle is full, and each element (space) in the file has a number in it, so when it iterates over each number, it does not find any errors or missing numbers. But when a partial file is saved, it cannot be opened back into the grid to start playing it again...
Your representation of a (sample) row is this:
1,2,,7,6,,,,5
But when you split that line on ,, you will get:
[1,2,7,6,5]
This is clearly not an array of length 9, so if (splitLine.length != 9) will return false. You must save a non-digit character to the text file that indicates an 'empty' space, or the split function will very rarely return a row of the correct length. It is possible to represent an entire Sodoku board with a single list of 81 characters, the digits 0 through 9 and an 'empty' character, no commas or line breaks needed. The key here is that the empty character is still required to maintain the topology of your data structure.
As a side note this:
if (c < ROWS - 1) {
saveFile.write(",");
}
Should probable reference COLS instead.
From reading your code it would seem to me that the offending line is:
if (splitLine[c].length() != 1 || !(Character.isDigit(splitLine[c].charAt(0)))) {
throw new IllegalArgumentException(...
In the function openPuzzle. This is because when saving a partially completed sudoku your file will look like "1,2,,3,,1,6,7,....." Now the empty cells when read in will have a string length of 0. So splitLine[c].length() != 1 will fail. To solve this i would suggest changing the code to be:
if (splitLine[c].length() > 0 || !(Character.isDigit(...
So that zero length characters (unfilled spaces) are accepted when loading it in.

Does a file have to be updated in some way for Java?

So I start with a textfile; this textfile at the start contains a number 3 (amount of woningen) 3 Woningen. I can read them with a Scanner without errors. I can also add a Woning without errors. If a Woning is added, the number on top of the file is incremented with 1.
Problem is as follows:
If a Woning has been added, the file has changed. The number is now 4, and a Woning has been added. However, if I want to read all the Woningen, Java returns an exception on the 4th Woning. So for some reason I can't read the 4th Woning.
What can be the cause of this? Do I have to save the file somehow after changes have been made to the file? Or something else has to be done?
Help is greatly appreciated :)!
EDIT
Note: Woning is the dutch word for House.
Code to read the file:
public static Portefeuille read (String infile) {
try {
Scanner sc = new Scanner (new File(infile));
ArrayList<Woning> wlijst = new ArrayList<Woning>();
Portefeuille p = new Portefeuille();
int woningen = sc.nextInt();
int i = 0;
while (i < woningen) {
sc.nextLine();
String tag = sc.nextLine();
wlijst.add(Woning.read(sc));
wlijst.get(i).setTag(tag);
//System.out.println(wlijst.get(i).getTag());
//System.out.println(wlijst.toString());
p.voegToe(wlijst.get(i));
i++;
}
sc.close();
return p;
}
catch (Exception e) {
System.out.println("Portefeuille: Exception is caught");
Portefeuille p = new Portefeuille();
return p;
}
}
Code to write to the file:
public static void writeToFile (Portefeuille port, int woningen) {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("Makelaar.txt", false)))) {
woningen = woningen + 1;
out.println(woningen);
ArrayList<Woning> wlijst = new ArrayList<Woning>();
wlijst = port.woninglijst;
for (int i = 0; i < wlijst.size(); i++) {
if (wlijst.get(i) instanceof KoopWoning) {
KoopWoning kw = (KoopWoning) wlijst.get(i);
KoopWoning.writeToFileK(kw, out);
}
else {
HuurWoning hw = (HuurWoning) wlijst.get(i);
HuurWoning.writeToFileH(hw, out);
}
}
out.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
System.out.println("writeToFile: Exception Caught");
}
}
File looks like this:
3
TE KOOP:
Emmalaan 23
3051JC Rotterdam
7 kamers
koopprijs 300000
energiepeil C
VERKOCHT:
Emmalaan 25
3051JC Rotterdam
5 kamers
vraagprijs 280000
energiepeil A
TE HUUR:
Javastraat 88
4078KB Eindhoven
3 kamers
huurprijs 500
I dont know what woningen is. But as far as I know, after adding the data to file, close the file and then try to read the data in file. This definition is always stuck in my mind that one should close the file after you've the finished your process. I can only guess whether you've done two java class for reading and writing or in a same class of writing and reading methods. Hereafter provide some codes so that all can atleast understand on what you're asking.

Looping through excel rows keeps given me an ArrayIndex...Exception

Okay so I am stuck and I am sure it is a simple solution. Basically I am beginning my initial conversion, or at least constructing a demo, to a keyword driven framework for selenium testing. Each row will contain data that will be used to drive the test. After the row is complete, the next row will contain the next test and so on. So I just started and I am having a little bit of trouble. Here is my code:
public List<String> getRowData(String row){
Sheet sheet = null;
List<String> getContents = new ArrayList<>();
try{
sheet = getWorkBook().getSheet("test");
for(int i=0; i<sheet.getRow(i).length; i++){
getRowData = sheet.getRow(i);
for(Cell rowData : getRowData){
System.out.print(String.format("Row info: %s\n", rowData.getContents()));
getContents.add(rowData.getContents());
}
}
}catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
System.out.print("This is an exception!");
} catch (NullPointerException np){
System.out.print("File does not exist!");
}return getContents;
}
The strings for the exceptions are just placeholders, not going to be final. But I am getting an ArrayIndex....Exception. I do understand a little why I am getting the error, but I am trying to obviously break out of the loop once the row or row content is empty. I implemented a condition such that
if(sheet.getRow(i) == null){
break;
}
But it still evaluated and provides the same exception. I am stuck and would like your help in trying to break out of the loop when there are no contents. Thank you
change for(int i=0; i<sheet.getRow(i).length; i++)
to:
for(int i = 0; i < sheet.getRows(); i++){
if(sheet.getRow(i) == null) break;
//rest of the code
}
But are you sure you want to break the loop on an empty row and not continue to the next row?

Reading From directories+sub-directories

this is a semi homework and I've been trying for ages but without luck,basically I'm doing a Search engine-Like program,where i read files in my directory + their sub directory's and Read the text files to search for a match,i searched endlessly but without clear answer so I'd appreciate if any one could help.
this was my best try but the problem with it that it only took the files from the sub directory and ignored the main/root directory,tried to figure out why but couldn't.
public void indexDirectory(File dir) {
for(int i=0;i<50;i++)
ls[i]=new LinkList();//array of Linked lists to store addresses of each Linked list that has a file
try{
files= dir.listFiles();
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory())
indexDirectory(files[i]);
if(files[i].isFile()){
if(files[i]!=null)
indexFile(files[i]);
} //end if(isFile)
} //end For loop
}catch(FileNotFoundException e){
System.out.println("error ");
}}
second version after serching the web and trying to emulate what i found,but didn't work sadly.
public void indexDirectory(File dir) {
for(int i=0;i<50;i++)
ls[i]=new LinkList();
try{
if(dir.isFile()){
indexFile(dir); //this method takes each directory and read the words and save them in
// array of linked list
}
else if(dir.isDirectory()){
files= dir.listFiles();
if(files!=null) {
for (int i = 0; i < files.length; i++) {
if(files[i].isDirectory()){
indexDirectory(files[i]); //recursive call
}}
}catch(FileNotFoundException e){
System.out.println("error ");
}}
In the first version, you loop through the entire file.length and check only for file.isDirectory and after that (ie. after all files/folders have been traversed) you check if it is a file. That's why you cannot read through current directory's files. Simply put the
if(files[i].isFile()){
if(files[i]!=null)
indexFile(files[i]); //the method to read from these files and save to array of lists.
}
block in for loop and it should work in the first version.
One more thing I didn't understand the purpose of ls variable here.

Categories

Resources