Problem in reading input form files while parsing them in javacc
I need to parse a language called DISP (delay insensitive sequential processes) using javacc. I need help with reading the input which we parse, eg for a matched brace example i dont want to just check if all the braces are matched, i also want to do something everytime i read a brace.
Is declaring tokens and using token.image the only way?
and can anyone explain what "parser object" "token manager" etc are and how the whole thing works, in simple words. The documents have details but i keep getting getting lost in them
import java.io.*;
import java.util.*;
import javax.comm.*;
public class SimpleRead implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
public static void main(String[] args) {
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
//if (portId.getName().equals("/dev/term/a")) {
SimpleRead reader = new SimpleRead();
public SimpleRead() {
try {
serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
} catch (PortInUseException e) {}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(9600,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
} catch (UnsupportedCommOperationException e) {}
readThread = new Thread(this);
readThread.start();
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException e) {}
public void serialEvent(SerialPortEvent event) {
switch(event.getEventType()) {
case SerialPortEvent.BI:
case SerialPortEvent.OE:
case SerialPortEvent.FE:
case SerialPortEvent.PE:
case SerialPortEvent.CD:
case SerialPortEvent.CTS:
case SerialPortEvent.DSR:
case SerialPortEvent.RI:
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
System.out.print(new String(readBuffer));
} catch (IOException e) {}
break;
}
Similar Messages
-
Problem in reading no. of files and writing into a single file
Hi,
Iam with Problem in reading no. of files and writing into a single file....
Iam reading no. of files stored in local directory.......
Iam able to read and print the data in files successfully....but while writing..only first file is being written...and the next files are not written in my output file...
plz tell me my mistake....I hope Iam doing some mistake while writing into file...PLz help.....
Basically my code structure is like this....
import java.io.*;
import java.util.regex.*;
import java.util.*;
import java.text.*;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFCell;
class Writing {
public static void main(String args[]) throws Exception {
FileOutputStream fileOut = new FileOutputStream("ServerResult.xls"); //my output file
int counter = 1;
File dir = new File("C:/Perform/ServerLogs");
String[] children = dir.list();
if( children == null)
System.out.println("The Directory mentioned does not exist");
else {
for (int fileNo = 0; fileNo < children.length; fileNo++ ) { //Files iteration starts
String filename = children[fileNo];
File logFile = new File(filename);
FileReader logFileReader = new FileReader(logFile);
BufferedReader logReader = new BufferedReader(logFileReader);
StringBuffer sBuf = new StringBuffer(5000);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet();
HSSFRow rowTitle;
HSSFRow rowReq;
HSSFRow rowRes;
String aLine = null;
boolean skip = false;
boolean readed = false;
boolean initReq = false;
boolean flag = false;
long requestTime = 0;
long responseTime = 0;
long recdTime = 0;
long sentTime = 0;
long hasTime = 0;
long presentTime = 0;
int hasCalls = 0;
Pattern startMessage = Pattern.compile("^<MESSAGE.*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern requestMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<ActName>(.*)</ActName>.*", Pattern.DOTALL);
Pattern requestMessage1 = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"RequestMsg.\".*ID=\".*_"+args[0]+"\".*<Svc id=\"(.*)\">.*", Pattern.DOTALL);
Pattern responseMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern initMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"HostConnInit\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern initResMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*", Pattern.DOTALL);
Pattern initResIDMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"ResponseMsg\".*ID=\"null\".*<IATA>"+args[0]+"</IATA>.*", Pattern.DOTALL);
Pattern sentMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgSentInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
Pattern rcvdMessage = Pattern.compile("^<MESSAGE.*TS=\"(.*)\" CATEGORY=\"DCMsgRcvdInfo\".*ID=\".*_"+args[0]+"\".*", Pattern.DOTALL);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
DecimalFormat dcf = new DecimalFormat("########.##");
String actName = "";
if (fileNo ==0)
rowTitle = sheet.createRow((short)0);
rowTitle.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)0).setCellValue("Req/Res");
rowTitle.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)1).setCellValue("Action");
rowTitle.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)2).setCellValue("Server Time(in ms)");
rowTitle.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)3).setCellValue("Request Vs Response Time in Server(in ms)");
rowTitle.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)4).setCellValue("Time Taken By HAS/HOST(in ms)");
rowTitle.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)5).setCellValue("No. of HAS calls");
rowTitle.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
rowTitle.createCell((short)6).setCellValue("Data Size");
//wb.write(fileOut);
while((aLine=logReader.readLine()) != null) {
if(aLine.startsWith("<MESSAGE TYPE=\"EVENT\"")) {
Matcher m = startMessage.matcher(aLine);
if(m.find()) {
sBuf.setLength(0);
sBuf.append(aLine);
skip = false;
initReq = false;
m = initMessage.matcher(aLine);
if(m.find()) {
initReq = true;
} else {
if(initReq) {
m = initResMessage.matcher(aLine);
if(m.find()) {
sBuf.setLength(0);
sBuf.append(aLine);
skip = false;
} else if(aLine.startsWith("</MESSAGE>")) {
if(!skip) {
sBuf.append(aLine);
readed = true;
} else if(!skip){
sBuf.append(aLine);
if(!skip && readed) {
String tempStr = sBuf.toString();
if(tempStr.length() > 0) {
boolean reqMatched = false;
Matcher m = null;
if(initReq) {
m = initMessage.matcher(tempStr);
actName = "Intialization";
} else {
m = requestMessage.matcher(tempStr);
String time = "";
if(m.find()) {
reqMatched = true;
for (int i=1; i<=m.groupCount(); i++) {
String groupStr = m.group(i);
if(i == 1) {
time = groupStr;
} else if(i == 2) {
actName = groupStr;
} else if(!initReq){
m = requestMessage1.matcher(tempStr);
if(m.find()) {
reqMatched = true;
for (int i=1; i<=m.groupCount(); i++) {
String groupStr = m.group(i);
if(i == 1) {
time = groupStr;
} else if(i == 2) {
actName = groupStr;
if(time.length() > 0 ) {
try{
requestTime = sdf.parse(time).getTime();
}catch(Exception ex){}
System.out.println("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
//bw.write("Request,"+actName+","+time+",,,,"+dcf.format(((double)time.length()/1024.0))+"K");
String reqDataSize = dcf.format(((double)time.length()/1024.0))+"K" ;
rowReq = sheet.createRow((short)counter);
rowReq.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)0).setCellValue("Request");
rowReq.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)1).setCellValue(actName);
rowReq.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)2).setCellValue(time);
rowReq.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)3).setCellValue("");
rowReq.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)4).setCellValue("");
rowReq.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)5).setCellValue("");
rowReq.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
rowReq.createCell((short)6).setCellValue(reqDataSize);
counter = counter +1;
System.out.println("counter is "+counter);
Matcher l = sentMessage.matcher(tempStr);
Matcher k = rcvdMessage.matcher(tempStr);
if(l.find()) {
for (int i=1; i<=l.groupCount(); i++) {
String groupStr2 = l.group(i);
try{
sentTime = sdf.parse(groupStr2).getTime();
}catch(Exception ex){}
if(k.find())
for(int j=1;j<=k.groupCount(); j++) {
String groupStr1 = k.group(j);
try{
recdTime = sdf.parse(groupStr1).getTime();
}catch(Exception ex){}
presentTime = (recdTime - sentTime);
hasTime = hasTime + presentTime;
hasCalls = hasCalls +1;
if(!reqMatched) {
if(initReq) {
m=initResIDMessage.matcher(tempStr);
} else {
m=responseMessage.matcher(tempStr);
if(m.find()) {
for (int i=1; i<=m.groupCount(); i++) {
String groupStr = m.group(i);
try{
responseTime = sdf.parse(groupStr).getTime();
}catch(Exception ex){}
String resDataSize = dcf.format(((double)tempStr.length()/1024.0))+"K" ;
rowRes = sheet.createRow((short)(counter));
rowRes.createCell((short)0).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)0).setCellValue("Response");
rowRes.createCell((short)1).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)1).setCellValue(actName);
rowRes.createCell((short)2).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)2).setCellValue(groupStr);
rowRes.createCell((short)3).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
rowRes.createCell((short)3).setCellValue((responseTime - requestTime));
rowRes.createCell((short)4).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
rowRes.createCell((short)4).setCellValue(hasTime);
rowRes.createCell((short)5).setCellType(HSSFCell.CELL_TYPE_NUMERIC);
rowRes.createCell((short)5).setCellValue(hasCalls);
rowRes.createCell((short)6).setCellType(HSSFCell.CELL_TYPE_STRING);
rowRes.createCell((short)6).setCellValue(resDataSize);
hasTime = 0;
hasCalls = 0;
counter = counter + 1 ;
sBuf.setLength(0);
readed = false;
wb.write(fileOut);
} // End of for (int fileNo = 0; fileNo < children.length; fileNo++ )
} //End of else
fileOut.close();
} //End of public static void main
} // End of ClassFirst of all, use [code]-tags to make your code readable, please.
I didn't do a complete inspection of your code (because it's too much and unreadable as it is) and I don't know POI, but creating a new HSSFWorkbook for each input file sounds fishy to me ... try re-using the workbook and just creating a new sheet in each iteration. -
Reached end of file while parsing error
I have a problem. It looks like my program has no errors but I get an error that says "reached end of file while parsing" (note: this is being developed in NetBeans). Can you help me?
class LongNumbers {
public static void main(String[] args) {
long numbers = 12345678910L;
int number = 2;
switch (number) {
case 1: System.out.println("One\nTwo\nThree\nFour\nFive\nSix\nSeven\nEight\nNine\nTen");
case 2: System.out.println(numbers);
int firstArg;
if (args.length > 0) {
try {
firstArg = Integer.parseInt(args[0]);
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer");
System.exit(1);
}Oh, nevermind. I found the problem. The admins can delete this if they want.
-
How can I read the EXCEL file while Program is running in background.
Hi all Expert,
How can I read the EXCEL file while Program is running in background.
Thanksyou need to place ur excel file on application server and follow this thread: Reading an Excel file from the application server?
loots of information if you can search forum.. thanks -
Problem in reading a resource file form JAR
Problem in finding a resource file from the jar.....
I have my code in the following directory structure
rootDir -
libDir -
XMLEntities.res
modelDir -
File1
File2
File3
Step1 - I create a jar file with root as modelDir and with all its files.
Step2 - I add XMLEntities.res also to the root of the jar
If I run my application using
java -classpath ;C:\aip_build\build_dm\rmi_server_files\dm.jar; model.data_model.ActivateDataManager
My application which uses Xalan.jar (lyong under ext directory in jdk) does not find XMLEntiries.res.
If I use my application as under without creating jar my application does find XMLEntites.res
Can anyone tell me why the application can not find the XMLEntities.res inside jar?Sorry I missed one line............
Problem in finding a resource file from the jar.....
I have my code in the following directory structure
rootDir -
----libDir -
--------XMLEntities.res
----modelDir -
--------File1
--------File2
--------File3
Step1 - I create a jar file with root as modelDir and
with all its files.
Step2 - I add XMLEntities.res also to the root of the
jar
If I run my application using
java -classpath
;C:\aip_build\build_dm\rmi_server_files\dm.jar;
model.data_model.ActivateDataManager
My application which uses Xalan.jar (lyong under ext
directory in jdk) does not find XMLEntiries.res.
If I use my application as under without creating jar
my application does find XMLEntites.res
java -classpath
;C:\aip_build\build_dm\rmi_server_files\;C:\aip_build\b
ild_dm\rmi_server_files\lib
model.data_model.ActivateDataManager
Can anyone tell me why the application can not find
the XMLEntities.res inside jar?try loading the resources as a InputStream
something like :
InputStream is = NameOfLoadingClass.class.getClassLoader().getResourceAsStream("XMLEntities.res");
Hope this might help you in some way. -
Problem in reading the excel file path in WINDOWs machine from UNIX environ
Hello friends,
My requirement is to read each row of the excel sheet and sent that row to the database. I have implemented it by using jxl and apache poi framework. locally in my WINDOWS machine it is working fine..
But when i deploy the code in UNIX machine. My application runs on a Unix server , trying to read the excel file in WINDOWS environment. I am not able to retrieve the file path. for ex : C:\Documents and Settings\sabbanik\My Documents\KARUNAKAR\excel.xls
I am getting error in this line
workbook = Workbook.getWorkbook(filepath)
Error message : input file not found.
Thanks in advance..You said: I am getting error in this line workbook = Workbook.getWorkbook(filepath) >
Based on this, I will assume you are trying to use OLE to access information about the Excel file. As mentioned by Andreas, your code will be executing on the server (Unix) and since Excel isn't on the server (and cannot be) an error will result. OLE can only be used in Windows environments (client or server). To access client side OLE calls and content, you need a java bean and Excel installed on the client machine. Oracle provides WebUtil as an option to writing your own Java Bean. To use this, you will need to be running Forms 10.1.2 or newer. Details can be found here along with a demo:
http://www.oracle.com/technetwork/developer-tools/forms/webutil-090641.htm -
Problem in reading the form parameter.
Hi All,
I have made a HTML with Following Tag
<form name="uploadForm" action="upload.jsp" enctype="multipart/form-data" method="post">
as i made the enctype="multipart/form-data" i am not able to read the Form parameter that i got in the File tag of the HTML page.
Task is to :
Upload 4 images from the HTML page and the uploading Code is present in the JSP that has to read the File name and Upload the Images.
While making request.getParameter("File1");
Dosen't work here.
can Any one provide the Solution for that.
regardsHello Ankur,
If you make a 'where used list' on this function, you will see that this parameter is never used in the standard. You will always see something like :
CALL FUNCTION 'CRM_SCHEDLIN_CONVERT_TZTF_IO'
EXPORTING
IV_FROM_TIME = LS_SCHEDLIN_WRK-FROM_TIME
IV_FROM_TIMEZONE = LS_SCHEDLIN_WRK-FROM_TIMEZONE
IV_TO_TIME = LS_SCHEDLIN_WRK-TO_TIME
IV_TO_TIMEZONE = LS_SCHEDLIN_WRK-TO_TIMEZONE
IMPORTING
EV_FROM_IO = LS_SCHEDLIN_WRK-FROM_TIME_IO
EV_TO_IO = LS_SCHEDLIN_WRK-TO_TIME_IO.
So I think you can do the same.
Regards,
Frédéric -
Help! Problem with reading objects from file
I wrote a "Library" program for an assignment, and one of the requirements is that the library store all of its information to file upon exit, and reload this information from file when run.
Well, the writing to file part is working. I'm using a FileOutputStream object and an ObjectOutputStream object. I can tell from the file size of the .dat file that information is going into it.
But what I can't do is read from file. For that, I'm using a FileInputStream and an ObjectInputStream. I keep getting this exception:
java.io.EOFException
at java.io.DataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream$BlockDataInputStream.readInt(Unknown Source)
at java.io.ObjectInputStream.readInt(Unknown Source)
at Library.readDataFromFile(Library.java:350)
at Library.<init>(Library.java:63)
at LibraryDriver.main(LibraryDriver.java:6)I looked this exception up and it says it's thrown when a data input stream unexpectedly ends....But I am instantiating the input streams just before I try to read from file:
fileInStream = new FileInputStream(libraryFile);
objInStream = new ObjectInputStream(fileInStream);
Object[] objectArray = new Object[objInStream.readInt()];Both input streams have methods that "return the number of bytes that can be read from this file input stream without blocking". Just for kicks, I tried writing that number to the console.
For the FileInputStream, I get 404 bytes.
For the ObjectInputStream, I get 0 bytes.
So I guess it's a problem with the ObjectInputStream? Anyone have any suggestions as to how I can fix this, please?Yep, here's the relevant code from the writeToFile() method:
for (int i = 0; i < libraryAuthors.length; i++) {
currentAlphaAuthorList = libraryAuthors;
for (int j = 0; j < currentAlphaAuthorList.size(); j++) {
currentAuthor = (Author) currentAlphaAuthorList.get(j);
objOutStream.writeObject(currentAuthor);
objOutStream.flush();
objOutStream.close(); -
Problem in reading an Image file from a Output Stream.
I am having problem reading a JPEG file. Actually i am sending JPEG file using UDP from the client. I am using this code to convert to a byte array to transmit the file:
DataInputStream inStream = new DataInputStream(new FileInputStream("src/Bgamex.jpg"));
String str1 = inStream.toString();
byte[] bindata = new byte[65500];
bindata = str1.getBytes();
On the server side, I am using these lines to convert the bytes to a file again but it seems to be that its not working. Its making file but with a bigger size & like garbage in it, showing nothing:
byte[] buf = new byte[65500];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
buf = packet.getData();
java.io.OutputStream fos = new java.io.FileOutputStream("Bga.jpg");
fos.write(buf);
Could somebody lemme know the problem in converting the file.
Thanx.I propose you to perform this simple test to see by yourself: final String BIN_FILENAME = "somebytes.bin";
byte[] bin = {5, 4, 3, 2, 1};
FileOutputStream out = new FileOutputStream(BIN_FILENAME);
out.write(bin);
out.flush();
out.close();
byte[] bindata;
DataInputStream in1 = new DataInputStream(new FileInputStream(BIN_FILENAME));
String str = in1.toString();
in1.close();
bindata = str.getBytes();
System.out.print("Bytes read with in1>");
for (int i=0; i<bindata.length; i++) System.out.print(bindata);
System.out.println();
FileInputStream in2 = new FileInputStream(BIN_FILENAME);
bindata = new byte[65505];
int bread = in2.read(bindata, 0, in2.available());
in2.close();
System.out.print("Bytes read with in2>");
for (int i=0; i<bread; i++) System.out.print(bindata[i]);
System.out.println(); -
Problem in reading from excel file with my requirement
Hi,
Below is my input excel file format
A XXX
B XXX
C XXX
D E F G H I J K L M N
XX XX XX XX.........................XX
All the A...N are headings and XX's are values.
How should I define an internal table for this requirement. I am using FM TEXT_CONVERT_XLS_TO_SAP to read input file.
Please let me know the correct way to define internal table for the above file format.
Regards,
CherithaHello Cheritha,
Your final internal table(t_final) should have all the fields viz. A, B, C, D etc.
You need to read the file to an internal table say t_data. In the internal table t_data, the field values will be each row in this internal table.
So you need to loop on t_data and based on the field name assign it to the corresponding field in the internal table t_final.
Hope this is clear if any clarification please do reply
Regards
Farzan -
Problem with reading from a file
`HI,
i am trying to read from a text file... using following piece of code
try{
BufferedReader in = new BufferedReader( new FileReader(fileName), 100000);
while (in.readLine() != null)
temp = in.readLine();
in.close();
in = null;
} catch(Exception e) {System.err.println(e); }
System.out.println(temp);
text contains almost 7500 words...
but when i run this piece of code... output i got is NULL
... i don't know what i am doing wrong...
any suggestions
<Thanx in advance >while (in.readLine() != null)Right here, you are reading in the file, but you don't store the content.
temp = in.readLine();By the time you reach here, you have already read in the whole file, so there is nothing left to read. That's why temp is assigned null -
Problem with reading from bin file into Vector
What am I doing wrong? It works fine to write the vector to the bin file and then read from it. But if I try just to read from the file it wont work.
Does anybody has any good advice to give when it comes to reading data form a bin file??
import javax.swing.*;
import java.util.*;
import java.io.*;
class Binaerfil
public static void main (String [] args) throws IOException, ClassNotFoundException{
ObjectOutputStream utFil = new ObjectOutputStream (new FileOutputStream("HighScoreLista.bin"));
int po = 50;
Spelare s;
Spelare s1, s2, s3, s4, s5,s6,s7,s8,s9,s10;
String f�rNamn;
Vector v = new Vector();
s1 = new Spelare("Mario", 100);
s2 = new Spelare("Tobias",90 );
s3 = new Spelare("Sanja", 80 );
s4 = new Spelare("Marko", 70 );
s5 = new Spelare("Sofia", 60 );
s6 = new Spelare("Kalle", 50 );
s7 = new Spelare("Lisa", 40 );
s8 = new Spelare("Pelle", 30 );
s9 = new Spelare("Olle", 20 );
s10 = new Spelare("Maria",10 );
v.add(s1);
v.add(s2);
v.add(s3);
v.add(s4);
v.add(s5);
v.add(s6);
v.add(s7);
v.add(s8);
v.add(s9);
v.add(s10);
System.out.println ("Before writing to file");
System.out.println(v);
//Write to file
utFil.writeObject (v);
utFil.close();
ObjectInputStream inFil = new ObjectInputStream (new FileInputStream("HighScoreLista.bin"));
v =(Vector) inFil.readObject();
System.out.println (v);
inFil.close();
}Because what you are writing to the file is a vector, that is all you can get out. You are actually reading a single Object from the file which you can cast to a Vector, from which you can access the data stored inside. If you want to read the Spelare instances from the file, you will have to save them individually to the file. You will have to implement Serializable and look up the API to do that.
-
Problem with reading from DAT file. FileNotFound exception
Can't seem to find the issue here. Two files, one (listOfHockeyPlayers) reads from a DAT file a list of players. The other (HockeyPlayer) has just the constructor to make a new hockey player from the read data.
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;
import java.awt.*;
import java.io.*;
public class ImportHockeyPlayers
private ArrayList<HockeyPlayer> listOfHockeyPlayers = new ArrayList<HockeyPlayer>();
public ImportHockeyPlayers(String fileName)
throws FileNotFoundException
try
Scanner scan = new Scanner(new File(fileName));
while (scan.hasNext())
//Uses all the parameters from the HockeyPlayer constructor
String firstName = scan.next();
String lastName = scan.next();
int num = scan.nextInt();
String country = scan.next();
int dob = scan.nextInt();
String hand = scan.next();
int playerGoals = scan.nextInt();
int playerAssists = scan.nextInt();
int playerPoints = playerGoals + playerAssists;
//listOfHockeyPlayers.add(new HockeyPlayer(scan.next(),scan.next(),scan.nextInt(),scan.next(),scan.nextInt(),scan.next(),
//scan.nextInt(),scan.nextInt(),scan.nextInt()));
catch(FileNotFoundException e)
throw new FileNotFoundException("File Not Found!");
public String toString()
String s = "";
for(int i = 0; i < listOfHockeyPlayers.size(); i++)
s += listOfHockeyPlayers.get(i);
return s;
public class HockeyPlayer
private String playerFirstName;
private String playerLastName;
private int playerNum;
private String playerCountry;
private int playerDOB;
private String playerHanded;
private int playerGoals;
private int playerAssists;
private int playerPoints;
public HockeyPlayer(String firstName, String lastName, int num, String country, int DOB,
String hand, int goals, int assists, int points)
this.playerFirstName = firstName;
this.playerLastName = lastName;
this.playerNum = num;
this.playerCountry = country;
this.playerDOB = DOB;
this.playerHanded = hand;
this.playerGoals = goals;
this.playerAssists = assists;
this.playerPoints = goals + assists;
DAT File
Wayne Gretzky 99 CAN 8/13/87 R 120 222
Joe Sakic 19 CAN 9/30/77 L 123 210These are all in early development, we seem to have the idea down but keep getting the odd FileNotFound exception when making an object of the ImportHockeyPlayers class with the parameter of the DAT file.
We might even be on the wrong track with an easier way to do this. To give you an idea of what we want to do...read from the file and be able to pretty much plug in al lthe players into a GUI with a list of the all the players.
Thanks for your time.Thanks for the tip on the date format...good to
know.
public static void main(String[] args)
GUI gui = new GUI();
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
}It's just being called in the main.
Throws this error:
GUI.java:39: unreported exception
java.io.FileNotFoundException; must be caught or
declared to be thrown
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
^This error is simply telling you that an exception may occur so you must enclose it in a try catch block or change the main method to throw the exception as follows
public static void main(String[] args) throws
java.io.FileNotFoundException {
GUI gui = new GUI();
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
}or
public static void main(String[] args) {
GUI gui = new GUI();
try {
ImportHockeyPlayers ihp = new
ImportHockeyPlayers("HockeyPlayers.dat");
catch (FileNotFoundException e) {
System.out.println("error, file not found");
}I would reccomend the second approch, it will be more helpful in debugging, also make sure that the capitalization of "HockeyPlayers.dat" is correct
hope that helps -
Problem in Reading a .PDF file
HI Friends,
I am reading a .pdf file from within java program using its java.io package.
I am able to read the file, but when I print the line read from file on to the screen, it all garbage. Its not in readable characters.
I guess its reagrding mismatch in Charcter Sets of original file and the stream with which I m reading the file.
So,if u know the solution plz suggest me.Hello Simple@java
Here's an exemple of a class that opens the File "rapport.pdf" located at the same place as the class.
Of course AcroRd32.exe is the name of Acrobat Reader which allows to read pdf files. You can get it on : adobe.com(http://www.adobe.com/products/acrobat/readstep2.html)
You will change "rapport.pdf" by the name of your pdf file.
Then execute "test()".
* Open the file "rapport.pdf"
public class test
public test()
Runtime a = Runtime.getRuntime();
try
a.exec("AcroRd32.exe rapport.pdf");
catch (Exception e)
System.out.println(e.getMessage());
Good luck ! -
Reading multiple text files and writing them to one text file
Hi,
I'm trying to read a number of text files and write them to a single master file. My program reads all the files but only writes the last one to the master file.
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
// Input/Output Classes
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.FileNotFoundException;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import java.awt.GridLayout;
public class Actor implements ActionListener
public static String DataRoot = "I:\\JAVA\\UBP\\DAT
public static JFrame SW = new JFrame();
public static JTextField txtSPath;
public static JTextArea txtTable;
public void actionPerformed( ActionEvent e )
String Command = e.getActionCommand();
if (Command.equals("Process") )
SetupWin();
ProcessAll();
public void SetupWin()
SW.setTitle("void");
SW.setSize(300,400);
SW.setLayout(new GridLayout(6,1));
txtSPath = new JTextField(40); SW.add(txtSPath);
txtTable = new JTextArea(10, 40); SW.add(txtTable);
SW.setVisible(true);
public void ProcessAll()
Process("Dunstable","Finance");
Process("Dunstable","Production");
Process("Dunstable","Sales");
public void Process(String Town, String Dept)
String SPath = DataRoot + Town + "
" + Dept + ".txt";
String MPath = DataRoot + "masterFile" + ".txt";
txtSPath.setText(SPath);
String message = "Trying " + SPath;
System.out.println(message);
String SlaveTable=message;
try// if following fails an exception is thrown
Scanner Slave = new Scanner(new FileInputStream(SPath)); // reads slave file
PrintWriter outputStream = null;
outputStream = new PrintWriter(new FileOutputStream(MPath));
while ( Slave.hasNextLine() ) // reads text line by line
//Read and output next record
String PartRecord = Slave.nextLine();
String FullRecord = Town + " " + PartRecord;
System.out.println(FullRecord);
outputStream.println(FullRecord);
Slave.close();
outputStream.close();
txtTable.setText(SlaveTable);
//An Exception Error would be THROWN by above & CAUGHT below
catch(FileNotFoundException e)
message = "Could Not Find " + SPath;
System.out.println(message); //console
txtSPath.setText(message); //window
catch(IOException e)
System.out.println("Slave I/O Problem " + SPath);
}Edited by: Ardour on Mar 4, 2008 1:53 PMI haven't looked closely, but my spidey sense tingles at this:
new FileOutputStream(MPath)This will clobber (erase) the previous contents of the file. Open in append mode:
new FileOutputStream(MPath, true)Of course, if the file exists before you run this code, you will end up append to the original contents. If that is not wanted, consider using File's delete method first.
Maybe you are looking for
-
Logic 9.1.7 download. Re-install
This is probably a stupid newbie question. I'm new to my Mac (lion) and new to Logic 9.1.7 I bought Logic as a download and I don't know where the file is to re-install after a system failure? I know I can use Time Machine but I would sleep easier if
-
How can I remove the underline from added text for tracing edits
We have a lot of content that includes underscores and when we use the track text edit feature added text is green and underlined. How can I change the properties of the added text to not be underlined?
-
Hi , I'm facing a problem in displaying a JSP page . I'm displaying records from the database on the page . I want to display only 20 records at a time . I have given the navigation facility for previous,first ,last ,next etc. I'm getting all the rec
-
Brand new 5s turned itself off, now wont switch back on?
Using my phone was at about 20% battery, put it in my pocket and went to use 5 mins later and screen is black and wont switch back on. Has been sitting on charge for about 25 minutes and still nothing even when pressing or holding the home button or
-
Hi, Am new to this board. Looking at purchasing the above model through Apple and would like advise whether or not to upgrade the memory from 2 to 4 and the hard drive from 120 to 160 (if at all) when I make this purchase. The reason I ask this is da