Reading from a text file in to an array, help please
I have the following
public class date extends Loans{
public int dd;
public int mm;
public int yyyy;
public String toString() {
return String.format( "%d,%d,%d", mm, dd, yyyy );
public class Loans extends Borrowing {
public String name;
public String book;
public date issue;
public char type;
public String toString(){
return String.format( "%s, %s, %s, %s", name, book, issue, type );
import java.util.Scanner;
import java.io.*;
public class Borrowing extends BorrowingList {
private Loans[] Loaned = new Loans[20];
if i want to read in from a text file in to that array how do i do it?
sorry to keep bothering you and thanks loads for your help but now I am getting the following error mesage
C:\Documents and Settings\MrW\Menu.java:43: cannot find symbol
symbol : class IOException
location: class Menu
}catch(IOException e){
Note: C:\Documents and Settings\MrW\Borrowing.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error
BUILD FAILED (total time: 0 seconds)
for this line
}catch(IOException e){
Similar Messages
-
Reading from a text file into a 2D array
How do you read from a text file and put it into a 2D array? Or if someone could guide me to where I can find the information?
This tutorial shows how to read a file:
http://java.sun.com/docs/books/tutorial/essential/io/scanfor.html
This tutorial shows how to create arrays with multiple dimensions:
http://java.sun.com/docs/books/tutorial/java/nutsandbolts/arrays.html -
HOW TO WRITE AND READ FROM A TEXT FILE???
How can I read from a text file and then display the contents in a JTextArea??????
Also how can I write the contents of a JTextArea to a text file.
Extra Question::::::: Is it possible to write records to a text file. If you have not idea what I am talking about then ignore it.
Manny thanks,
your help is much appreciated though you don't know it!Do 3 things.
-- Look through the API at the java.io package.
-- Search previous posts for "read write from text file"
-- Search java.sun.com for information on the java.io package.
That should clear just about everything up. If you have more specific problems, feel free to come back and post them. -
How to read from a text file one character at a time?
Hello
I wish to read from a text file in a for loop and that on every iteration i read one charachter and proceed to the next one.
can anyone help me?
Lavilava wrote:
I wish to read from a text file in a for loop and that on every iteration i read one charachter and proceed to the next one.
can anyone help me?
Some additional comments:
You really don't want to read any file one character at a time, because it is highly inefficient. More typically, you read the entire file into memory with one operation (or at least a large chunk, if the file is gigantic) and then do the rest of the operations in memory. One easy way to analyze it one byte at a time would be to use "string to byte array" and then autoindex into a FOR loop, for example.
Of course you could also read the file directly as a U8 array instead of a string.
Message Edited by altenbach on 06-10-2008 08:57 AM
LabVIEW Champion . Do more with less code and in less time . -
Getting repeated values when reading from a text file.
I need to read from a text file. When the token encounters a particular word (command) I need to read the next line and perform some actions. However, this part is working but it is repeating the values again and again until it encounters the next particular word (command). Hope that someone will help me out, as always when I posted a problem in these forums.
SetOperations class - contains the set methods
// Imported packages.========================================================
import java.util.Vector;
import java.util.Iterator;
// Public class SetOperations.===============================================
public class SetOperations
// Instance variables.===================================================
private Vector v = null; // Creates new instance of vector.
protected int memberCount;
// Constructor.==========================================================
public SetOperations()
v = new Vector();
} // end constructor.
// Method isMember.======================================================
* Checks whether the element is already a member of the set.
* @return True if Vector v contains Object member.
public boolean isMember(Object member)
if (member != null) // only if Object member is not null.
return v.contains(member); // returns true if vector already contains member.
else
return false; // returns false if vector does not contain member.
} // end public boolean isMember(Object member).
// Method addMember.=====================================================
* Adds a member to the set.
* @return Adds Object member to Vector v.
public void addMember(Object member)
//if (! v.contains(member)) // only if element is not already a member.
if (isMember(member) == false) // only if element is not already a member.
v.add(member); // adds a member.
} // end public void addMember(Object member).
// Method countMember.===================================================
* Returns the number of members present in the vector.
* @return Number of elements present in the vector.
public int countMember()
return v.size();
} // end public int countMember().
// Method isSetEmpty.====================================================
* Returns true if set is empty.
* @return True if no elements are present in Vector v.
public boolean isSetEmpty()
return v.size() == 0; // returns 0 if no elements are present in the vector.
} // end of public boolean isSetEmpty().
// Method printMember.===================================================
* Displays member/s of the set.
* @return Prints element/s present in the vector.
public void printMember()
for (int i = 0; i < v.size(); i++) // iterates through present members.
System.out.println("[" + i + "] " + v.get(i)); // displays member/s present in the vector.
} // end of public void printMember().
} // end public class SetOperations.
SetTextLauncher class - reads from a text file and implements the set operations
// Imported packages.========================================================
import java.util.*;
import java.io.*;
// Public class SetTestLauncher.=============================================
public class SetTestLauncher
// Main method public static void main(String args[]).===================
public static void main(String args[])
displayFile("test.txt"); // outputs result from text file.
// method to display a file on screen
public static void displayFile (String textFile)
// Instance variables.===============================================
// Creates new instances of SetOperations.
SetOperations setA = new SetOperations();
SetOperations setB = new SetOperations();
SetOperations setC = new SetOperations();
SetOperations setD = new SetOperations();
SetOperations setE = new SetOperations();
// Initialisation.
String line = "", nextLine = "";
FileReader fr = null;
try
// Opens the file with the FileReader data sink stream.
fr = new FileReader(textFile);
// Converts the FileReader input stream with the BufferedReader processing stream.
BufferedReader br = new BufferedReader(fr);
// Iterates through text file reading lines until end of text lines.
while (line != null)
line = br.readLine(); // reads one line at a time.
if(line == null) break; // when the line is null break the loop.
// Creates a new instace of StringTokenizer.
StringTokenizer st = new StringTokenizer(line);
// Loops until there are no more tokens.
while (st.hasMoreTokens())
String token = st.nextToken(); // reads next token.
// Only if the token encounters the String "membera".
if(token.equals("membera"))
nextLine = br.readLine(); // gets next line.
setA.addMember(nextLine); // adds a member to the set.
// Displays members present in the set if vector is not empty.
if (! setA.isSetEmpty())
setA.printMember(); // print members present.
// Displays the number of member/s present in the vector.
System.out.println("Number of set members: " + setA.countMember());
// Catches and displays exceptions.
catch (FileNotFoundException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
catch (IOException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
finally
try
// if file is found
if (fr != null)
// close file
fr.close();
catch (IOException exp)
exp.printStackTrace();
} // end public static void main(String args[]).
} // end public class SetTestLauncher.Thanks for your interest. Please ignore SetOperations class, it is just the class containing the methods and it works correctly since I checked it without reading from a text file. I marked the part where I think lies my problem in class SetTestOperations.
The information in the text file is as follows:
membera
Hillman
membera
Skoda
membera
Honda
membera
Toyota
and the result is:
[0] Hillman
Number of set members: 1
[0] Hillman
[1] Skoda
Number of set members: 2
[0] Hillman
[1] Skoda
[2] Honda
Number of set members: 3
[0] Hillman
[1] Skoda
[2] Honda
[3] Toyota
Number of set members: 4
instead of just one set:
[0] Hillman
[1] Skoda
[2] Honda
[3] Toyota
Number of set members: 4
Hope it is easier to understand like this.
Regards
Marco
I need to read from a text file. When the token
encounters a particular word (command) I need to read
the next line and perform some actions. However, this
part is working but it is repeating the values again
and again until it encounters the next particular
word (command). Hope that someone will help me out,
as always when I posted a problem in these forums.
SetOperations class - contains the set
methods
// Imported
packages.=============================================
===========
import java.util.Vector;
import java.util.Iterator;
// Public class
SetOperations.========================================
=======
public class SetOperations
// Instance
e
variables.============================================
=======
private Vector v = null; // Creates new instance of
f vector.
protected int memberCount;
Constructor.==========================================
================
public SetOperations()
v = new Vector();
} // end constructor.
// Method
d
isMember.=============================================
=========
* Checks whether the element is already a member of
f the set.
* @return True if Vector v contains Object member.
public boolean isMember(Object member)
if (member != null) // only if Object member is not
ot null.
return v.contains(member); // returns true if
if vector already contains member.
else
return false; // returns false if vector does not
not contain member.
} // end public boolean isMember(Object member).
// Method
d
addMember.============================================
=========
* Adds a member to the set.
* @return Adds Object member to Vector v.
public void addMember(Object member)
//if (! v.contains(member)) // only if element is
is not already a member.
if (isMember(member) == false) // only if element
nt is not already a member.
v.add(member); // adds a member.
} // end public void addMember(Object member).
// Method
d
countMember.==========================================
=========
* Returns the number of members present in the
e vector.
* @return Number of elements present in the vector.
public int countMember()
return v.size();
} // end public int countMember().
// Method
d
isSetEmpty.===========================================
=========
* Returns true if set is empty.
* @return True if no elements are present in Vector
r v.
public boolean isSetEmpty()
return v.size() == 0; // returns 0 if no elements
ts are present in the vector.
} // end of public boolean isSetEmpty().
// Method
d
printMember.==========================================
=========
* Displays member/s of the set.
* @return Prints element/s present in the vector.
public void printMember()
for (int i = 0; i < v.size(); i++) // iterates
es through present members.
System.out.println("[" + i + "] " + v.get(i)); //
// displays member/s present in the vector.
} // end of public void printMember().
} // end public class SetOperations.
SetTextLauncher class - reads from a text file
and implements the set operations
// Imported
packages.=============================================
===========
import java.util.*;
import java.io.*;
// Public class
SetTestLauncher.======================================
=======
public class SetTestLauncher
// Main method public static void main(String
g args[]).===================
public static void main(String args[])
displayFile("test.txt"); // outputs result from
om text file.
// method to display a file on screen
public static void displayFile (String textFile)
// Instance
ce
variables.============================================
===
// Creates new instances of SetOperations.
SetOperations setA = new SetOperations();
// Initialisation.
String line = "", nextLine = "";
FileReader fr = null;
try
// Opens the file with the FileReader data sink
ink stream.
fr = new FileReader(textFile);
// Converts the FileReader input stream with the
the BufferedReader processing stream.
BufferedReader br = new BufferedReader(fr);
// Iterates through text file reading lines until
til end of text lines.
while (line != null)
line = br.readLine(); // reads one line at a
at a time.
if(line == null) break; // when the line is null
null break the loop.
// Creates a new instace of StringTokenizer.
StringTokenizer st = new StringTokenizer(line);
// Loops until there are no more tokens.
while (st.hasMoreTokens())
String token = st.nextToken(); // reads next
next token.
// Only if the token encounters the String
tring "membera".
if(token.equals("membera"))
// *****THE PROBLEM LIES HERE....I GUESS
// need to read the next line after encountering the word membera in text file
nextLine = br.readLine(); // gets next line.
setA.addMember(nextLine); // adds a member to
ber to the set.
// Displays members present in the set if
set if vector is not empty.
if (! setA.isSetEmpty())
setA.printMember(); // print members present.
// Displays the number of member/s present in
ent in the vector.
System.out.println("Number of set members: " +
s: " + setA.countMember());
// Catches and displays exceptions.
catch (FileNotFoundException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
catch (IOException exp)
System.out.println(exp.getMessage());
exp.printStackTrace();
finally
try
// if file is found
if (fr != null)
// close file
fr.close();
catch (IOException exp)
exp.printStackTrace();
} // end public static void main(String args[]).
} // end public class SetTestLauncher. -
Reading characters from a text file into a multidimensional array?
I have an array, maze[][] that is to be filled with characters from a text file. I've got most of the program worked out (i think) but can't test it because I am reading my file incorrectly. However, I'm running into major headaches with this part of the program.
The text file looks like this: (It is meant to be a maze, 19 is the size of the maze(assumed to be square). is free space, # is block, s is start, x is finish)
This didn't paste evenly, but thats not a big deal. Just giving an idea.
19
5..................
And my constructor looks like follows, I've tried zillions of things with the input.hasNext() and hasNextLine() to no avail.
Code:
//Scanner to read file
Scanner input = null;
try{
input = new Scanner(fileName);
}catch(RuntimeException e) {
System.err.println("Couldn't find the file");
System.exit(0);
//Set the size of the maze
while(input.hasNextInt())
size = input.nextInt();
//Set Limits on coordinates
Coordinates.setLimits(size);
//Set the maze[][] array equal to this size
maze = new char[size][size];
//Fill the Array with maze values
for(int i = 0; i < maze.length; i++)
for(int x = 0; x < maze.length; x++)
if(input.hasNextLine())
String insert = input.nextLine();
maze[i][x] = insert.charAt(x);
Any advice would be loved =DCode-tags sometimes cause wonders, I replaced # with *, as the code tags interprets # as comment, which looks odd:
******...*.........To your code: Did you test it step by step, to find out about what is read? You could either use a debugger (e.g., if you have an IDE) or system outs to get a clue. First thing to check would be, if the maze size is read correctly. Further, the following loops look odd:for(int i = 0; i < maze.length; i++) {
for(int x = 0; x < maze.length; x++) {
if (input.hasNextLine()) {
String insert = input.nextLine();
maze[x] = insert.charAt(x);
}Shouldn't the nextLine test and assignment be in the outer loop? And assignment be to each maze's inner array? Like so:for(int i = 0; i < maze.length; i++) {
if (input.hasNextLine()) {
String insert = input.nextLine();
for(int x = 0; x < insert.size(); x++) {
maze[i][x] = insert.charAt(x);
}Otherwise, only one character per line is read and storing a character actually should fail. -
Reading from a text file and displaying the contents with in a frame
Hi All,
I am trying to read some data from a text file and display it on a AWT Frame. The contents of the text file are as follows:
pcode1,pname1,price1,sname1,
pcode2,pname2,price2,sname1,
I am writing a method to read the contents from a text file and store them into a string by using FileInputStream and InputStreamReader.
Now I am dividing the string(which has the contents of the text file) into tokens using the StringTokenizer class. The method is as show below
void ReadTextFile()
FileInputStream fis=new FileInputStream(new File("nieman.txt"));
InputStreamReader isr=new InputStreamReader(fis);
char[] buf=new char[1024];
isr.read(buf,0,1024);
fstr=new String(buf);
String Tokenizer st=new StringTokenizer(fstr,",");
while(st.hasMoreTokens())
pcode1=st.nextToken();
pname1=st.nextToken();
price1=st.nextToken();
sname1=st.nextToken();
} //close of while loop
} //close of methodHere goes my problem: I am unable to display the values of pcode1,pname1,price1,sname1 when I am trying to access them from outside the ReadTextFile method as they are storing "null" values . I want to create a persistent string variable so that I can access the contents of the string variable from anywhere with in the java file. Please provide your comments for this problem as early as possible.
Thanks in advance.If pcode1,pname1,price1,sname1 are global variables, which I assume they are, then simply put the word static in front of them. That way, any class in your file can access those values by simply using this notation:
MyClassName.pcode1;
MyClassName.pname1;
MyClassName.price1;
MyClassName.sname1 -
Read words from a text file into an undefined array
Dear all,
Does anyone know how to read words in text file, seperated by all types of spaces ("_", "\n", "\t","\r","\f") and put them into a string array to be used later?
So far I can read the words using the Tokenizer but can't assign to array:
public class reader
StringTokenizer tokenizer = new StringTokenizer(input);
String[ ] array= null; //unknown size of array
int i=0;
while(tokenizer.hasMoreTokens())
array[i] = tokenizer.nextToken();
i++;
Any suggestions welcome!
thanks in advance!Hi
sorry wrote in a hurry ;) din c the problem clearly
there are two approaches
1) best approach for your problem is Vector or ArrayList, these would make life easy for you.
Always collections are better approach over arrays when the size is dynamic. However in your case the size cant be said to be DYNAMIC. coz the number of words will not grow / shrink during the runtime.. i know that number of words are not fixed but dynamic is something which will grow/shrink during runtime. but still collection is better approach.
2)dirty approach
use double dimensional array
String arr[][] = null;
then use one tokenizer for StringTokenizer(str,"\n");
using countTokens on this will give you number of lines.
use this to initialize array
arr = new String[lineCount][];
then iterate from 1 to lineCount and use 1 more tokenizer to get number of words for that line. use this number to initialize the column size for arr[i] like
arr[i] = new String[wordCount];
then store the token using nested for loops in this array
go for the 1st one ;) 2nd one is hedious n time consuming but both will work ;)
cheers
amey -
How to remove noisy data points read from a text file
Reading data measurements taken in from a txt file. How do I get rid of noise aside from going into the text file and deciding point by point what to delete.
Well going in point by point and deleting is certainly one way of going about it. Of course that would defeat the entire purpose of having this great programming enviroment that is capable of doing that kind of thing for us.
Is your text file small enough to upload? Obviously you know what the criteria are for judging whether or not a data point is acceptable so it should be simple enough to program. Give us a bit more information and I can assure you there will be a race between LabVIEW experts to see who can post the cleanest, simplest, and fastest piece of code that will do what you need. My wager is on altenbach, but there are a few others here that are almost as impressive. -
Read from a text file line by line
Hi,
I am new to Labview and I am trying to output a text file line by line. For example if my text file is
START
SETRPM 1000
WAIT 10s
RAMP RPM linear,1000,2000,2 MAF linear,5,7,2
WAIT 5s
RAMP RPM sine,2000,1500,3 MAF sine,7,3,3
END
I want it to output
START
SETRPM 1000
SETMAF 5 ...and so on
I tried modifying this code provided by Altenbach but it is still not working as I want it to. Can anyone direct me toward how I can fix this?
Thank you!
Your program does exactly what you asked it to do. In particular, it will repeat 10 times, at one per second, reading (and storing in String) the (unchanging) data that you bring in on the Shift Register. This data will consist of the first line of the (assumed-)multi-line file you specified.
I suppose your question is "Why is it only showing me one line?" This is where it really pays to "Read the Directions Carefully" (or, in this case, carefully read the Help for Read from Text File).
Bob Schor
P.S. -- I pointed your code at a text file of 7 lines on my PC. When I made a few small changes (including doing away with the silly For loop that shows the same thing over and over) , I got out an array, size 7, containing the lines of text. -
I have data that is in basic generic text file format that needs to be converted into Excel spreadsheet format. The data is much longer than 65536 lines, and in my code I haven't been able to figure out how to carry over the data into the next column. Currently the conversion is done manually and generates an Excel file that has a total of 30-40 full columns of data. Any suggestions would be greatly appreciated.
Thanks,
Darrick
Solved!
Go to Solution.No need to use nested For loops. No need for any loop anyway. You just have to use a reshape array function. The picture below shows how to proceed.
However, there may be an issue if your element number is not a multiple of the number of columns : zero value elements will be added at the end of the last column in the generated 2D array. Now the issue depends on the way you intend store the data in the Excel spreadsheet : you could convert the data as strings, replace the last zero values with empty strings, and write the whole 2D array to a file (with the .xls extension ) using the write to spreadsheet function. Only one (minimal) problem : define the number of decimal digits to be used;
or you could write the numeric array directly to a true Excel spreadsheet, using either the NI report generation tools or ActiveX commands, then replace the last elements with empty strings.
We need more input from you to decide how to solve these last questions.
Message Edité par chilly charly le 01-13-2009 09:29 PM
Chilly Charly (aka CC)
E-List Master - Kudos glutton - Press the yellow button on the left...
Attachments:
Example_VI.png 10 KB -
Reading data from a text file in to an array
Ok nobody tell me to search forums, read books, point me to the tutorials, i have done all that and still don't get it. so can some one help me write some code. I would like to read text from a file into an array. The array name is VehilcleList. Simplest was possible would be great. I dont want to use redirection, preferably using the filereader and filewriter class i imagine.
Your quick example:import java.io.*;
import java.util.*;
public class TryReadFileToArray {
public static void main(String[] args) {
File file = new File("C:/java/eclipse/workspace/scjp/vehicles.dat");
ArrayList vehicles = (ArrayList) getVehicles(file);
for (Iterator i = vehicles.iterator(); i.hasNext(); ) {
System.out.println(i.next());
public static List getVehicles(File file) {
ArrayList vehicles = new ArrayList();
try {
BufferedReader buf = new BufferedReader(new FileReader(file));
while (buf.ready()) {
String line = buf.readLine();
StringTokenizer tk = new StringTokenizer(line, ",");
ArrayList params = new ArrayList();
while (tk.hasMoreElements()) {
params.add(tk.nextToken());
Vehicle v =
new Vehicle(
(String) params.get(0),
(String) params.get(1),
(String) params.get(2),
Integer.parseInt((String) params.get(3)));
vehicles.add(v);
} catch (IOException ioe) {
System.err.println(ioe);
} catch (NumberFormatException nfe) {
System.err.println("Mileage not in correct format: " + nfe);
return vehicles;
class Vehicle {
// flesh out remaining instance members as needed
private String aMake;
public Vehicle(
String aMake,
String aModel,
String aRegistrationNumber,
int aMileage) {
this.aMake = aMake;
public String toString() {
return aMake;
}Uses the following file (vehicles.dat):Ford,Taurus,105BRQ,55000
Dodge,Neon,907JZH,105000
Ferrari,Testarossa,3ATM3,25412 -
Reading a Random Line from a Text File
Hello,
I have a program that reads from a text file words. I currently have a text file around 800KB of words. The problem is, if I try to load this into an arraylist so I can use it in my application, it takes wayy long to load. I was wondering if there was a way to just read a random line from the text file.
Here is my code, and the text file that the program reads from is called 'wordFile'
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
public class WordColor extends JFrame{
public WordColor(){
super("WordColor");
setSize(1000,500);
setVisible(true);
add(new WordPanel());
public static void main(String[]r){
JFrame f = new WordColor();
class WordPanel extends JPanel implements KeyListener{
private Graphics2D pane;
private Image img;
private char[]characterList;
private CharacterPosition[]positions;
private int charcounter = 0;
private String initialWord;
private File wordFile = new File("C:\\Documents and Settings\\My Documents\\Java\\projects\\WordColorWords.txt");
private FontMetrics fm;
private javax.swing.Timer timer;
public final static int START = 20;
public final static int delay = 10;
public final static int BOTTOMLINE = 375;
public final static int buffer = 15;
public final static int distance = 4;
public final static Color[] colors = new Color[]{Color.red,Color.blue,Color.green,Color.yellow,Color.cyan,
Color.magenta,Color.orange,Color.pink};
public static String[] words;
public static int descent;
public static int YAXIS = 75;
public static int SIZE = 72;
public WordPanel(){
words = readWords();
setLayout(new BorderLayout());
initialWord = getWord();
characterList = new char[initialWord.length()];
for (int i=0; i<initialWord.length();i++){
characterList[i] = initialWord.charAt(i);
setFocusable(true);
addKeyListener(this);
timer = new javax.swing.Timer(delay,new ActionListener(){
public void actionPerformed(ActionEvent evt){
YAXIS += 1;
drawWords();
if (YAXIS + descent - buffer >= BOTTOMLINE) lose();
if (allColorsOn()) win();
public void paintComponent(Graphics g){
super.paintComponent(g);
if (img == null){
img = createImage(getWidth(),getHeight());
pane = (Graphics2D)img.getGraphics();
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
pane.setFont(new Font("Arial",Font.BOLD,SIZE));
pane.setColor(Color.black);
drawThickLine(pane,getWidth(),5);
fm = g.getFontMetrics(new Font("Arial",Font.BOLD,SIZE));
descent = fm.getDescent();
distributePositions();
drawWords();
timer.start();
g.drawImage(img,0,0,this);
private void distributePositions(){
int xaxis = START;
positions = new CharacterPosition[characterList.length];
int counter = 0;
for (char c: characterList){
CharacterPosition cp = new CharacterPosition(c,xaxis, Color.black);
positions[counter] = cp;
counter++;
xaxis += fm.charWidth(c)+distance;
private void drawThickLine(Graphics2D pane, int width, int thickness){
pane.setColor(Color.black);
for (int j = BOTTOMLINE;j<BOTTOMLINE+1+thickness;j++){
pane.drawLine(0,j,width,j);
private void drawWords(){
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
drawThickLine(pane,getWidth(),5);
for (CharacterPosition cp: positions){
int x = cp.getX();
char print = cp.getChar();
pane.setColor(cp.getColor());
pane.drawString(""+print,x,YAXIS);
repaint();
private boolean allColorsOn(){
for (CharacterPosition cp: positions){
if (cp.getColor() == Color.black) return false;
return true;
private Color randomColor(){
int rand = (int)(Math.random()*colors.length);
return colors[rand];
private void restart(){
charcounter = 0;
for (CharacterPosition cp: positions){
cp.setColor(Color.black);
private void win(){
timer.stop();
newWord();
private void newWord(){
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
repaint();
drawThickLine(pane,getWidth(),5);
YAXIS = 75;
initialWord = getWord();
characterList = new char[initialWord.length()];
for (int i=0; i<initialWord.length();i++){
characterList[i] = initialWord.charAt(i);
distributePositions();
charcounter = 0;
drawWords();
timer.start();
private void lose(){
timer.stop();
pane.setColor(Color.white);
pane.fillRect(0,0,getWidth(),getHeight());
pane.setColor(Color.red);
pane.drawString("Sorry, You Lose!",50,150);
repaint();
removeKeyListener(this);
final JPanel p1 = new JPanel();
JButton again = new JButton("Play Again?");
p1.add(again);
add(p1,"South");
p1.setBackground(Color.white);
validate();
again.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent evt){
remove(p1);
addKeyListener(WordPanel.this);
newWord();
private String getWord(){
int rand = (int)(Math.random()*words.length);
return words[rand];
private String[] readWords(){
ArrayList<String> arr = new ArrayList<String>();
try{
BufferedReader buff = new BufferedReader(new FileReader(wordFile));
try{
String line = null;
while (( line = buff.readLine()) != null){
line = line.toUpperCase();
arr.add(line);
finally{
buff.close();
catch(Exception e){e.printStackTrace();}
Object[] objects = arr.toArray();
String[] words = new String[objects.length];
int count = 0;
for (Object o: objects){
words[count] = (String)o;
count++;
return words;
public void keyPressed(KeyEvent evt){
char tempchar = evt.getKeyChar();
String character = ""+tempchar;
if (character.equalsIgnoreCase(""+positions[charcounter].getChar())){
positions[charcounter].setColor(randomColor());
charcounter++;
else if (evt.isShiftDown()){
evt.consume();
else{
restart();
drawWords();
public void keyTyped(KeyEvent evt){}
public void keyReleased(KeyEvent evt){}
class CharacterPosition{
private int xaxis;
private char character;
private Color color;
public CharacterPosition(char c, int x, Color col){
xaxis = x;
character = c;
color = col;
public int getX(){
return xaxis;
public char getChar(){
return character;
public Color getColor(){
return color;
public void setColor(Color c){
color = c;
}I thought that maybe serializing the ArrayList might be faster than creating the ArrayList by iterating over each line in the text file. But alas, I was wrong. Here's my code anyway:
class WordList extends ArrayList<String>{
long updated;
WordList readWordList(File file) throws Exception{
WordList list = new WordList();
BufferedReader in = new BufferedReader(new FileReader(file));
String line = null;
while ((line = in.readLine()) != null){
list.add(line);
in.close();
list.updated = file.lastModified();
return list;
WordList wordList;
File datFile = new File("words.dat");
File txtFile = new File("input.txt");
if (datFile.exists()){
ObjectInputStream input = new ObjectInputStream(new FileInputStream(datFile));
wordList = (WordList)input.readObject();
if (wordList.updated < txtFile.lastModified()){
//if the text file has been updated, re-read it
wordList = readWordList(txtFile);
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
output.writeObject(wordList);
output.close();
} else {
//serialized list does not exist--create it
wordList = readWordList(txtFile);
ObjectOutputStream output = new ObjectOutputStream(new FileOutputStream(datFile));
output.writeObject(wordList);
output.close();
}The text file contained one random sequence of letters per line. For example:
hwnuu
nhpgaucah
zfbylzt
hwnc
gicgwkhStats:
Text file size: 892K
Serialized file size: 1.1MB
Time to read from text file: 795ms
Time to read from serialized file: 1216ms -
Is it possible to read/write to text file without deleting it?
I know how to read from a text file and how to write to a text file. The problem that i have is i need to use a text file to store data for my application to read and also for my application to write. I would like it if i could write two programs really, one reads, the other is used to update the text file. This file is a list of verbs. I thought about using databases but i couldn't get them to work. I downloaded MySQL server 5.0 and installed it. I then downloaded the driver from http://www.mysql.com/products/driver and ran the auto installer. it said everything worked out perfectly but when i try these lines:
Class.forName("com.mysql.jdbc.Driver");
I get a SQLException that says no suitible driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
( I thought this driver came with the JDK but i guess not, i just read about it in a java book)
I get a ClassNotFoundException
that just says sun.jdbc.odbc.JdbcOdbcDriver
So yeah, SQL is pretty much not working. I need a solution to my problem, either by using text files, or a different type of database. I heard you could use excel to create a database but i have no idea how and i hear microsoft access could also do this, however i don't have microsoft access and i don't intend on paying for it. So, here are my questions:
1st, is there a tutorial on using excel databases in java programs
(if not)
2nd is there a way to read/write/update a text file without deleting it?
(if not)
3rd is there a way to get SQL working, i have windows vista this could be the problem
(if not)
4th what could i do to store information on the hd for reading and modifying later?
thanks, lateralusA database might be overkill just for a list of words.
Thoughts:
<ul>
<li>What is the extent of your "file updating"? If you are just appending to the file, opening it in append mode will keep the file from being clobbered.</li>
<li>Otherwise, why not create new files instead of editting them? The file names could include a version number or timestamp, allowing the reader to select the newest one.
</li>
</ul> -
Interactive Bar/pie chart and line graph, data from excel/text file -urgent
Hi,
I have a huge data in excell sheet which keeps updating every month. Data basically consists of service provider and there respective subscribers from various regions of the country over the years. The requirement is to give the viewers an interactive page where in they can make various combinations and can compare, cross examine data according to thier choice.
We want the pie chart / bar graph or line graph to be created on the fly according to the combination made by the user.
The site is hosted on a red hat linux server. how can a connection to the excel spreadsheet be made or is it possible to read from the text file if the entire data is exported to a text file.
Is there any ready made tool/code available which can be customised according to the need.
Thanx in advance
Regards
PrakashI certainly wouldn't pay for the graphing package at the previous link. check out http://www.object-refinery.com/jfreechart/ for a free, open-source, much better looking graphing package.
Maybe you are looking for
-
Connection problem with new database
Hi Installed new database on my windows machine successfully while connectting as sys user error ORA-12500:TNS: listner failed to start dedicated server process wlile connecting toad and sqlplus
-
Hauppauge 850 works, but not through MythTV!
I have a Hauppauge 850 (model 72301, 2040:7240). I have loaded the necessary drivers, and firmware. I can get video working just fine in tvtime (no audio, but I hear that this is normal), VLC works through DVB, but the MythTV program seems to be inca
-
Service Entry Sheet creation!!!!
Hi all, I am working on service procurement with ECS scenario.The Service Entry Sheet in the backend R/3 system is subject to release strategy(for a material group). Whenever I create a Service Entry Sheet(SES) based on a EBP PO, then the SES is subj
-
"Went to work on my photos and something popped up that says, file 0ff-line or missing. This has never happened before. Can someone help? thank you!
-
Showing Closed Complaints for a IBASE in CRM
Hi Guys, I have a requirement like : i need to show complaints those are closed for a IBASE.For Example : if i create a complaints in complaint transaction and assign one IBASE to these and saved it.Now my requrement is to check for all compal