Seperate read and write thread example
hi.
can anyone tell me a simplest way to implement thread to read and write from the socket seperately without blocing each other?
how do i create seperate threads for a client to write and read from a serversocket?
maskeeeee
hi.
can anyone tell me a simplest way to implement thread
to read and write from the socket seperately without
blocing each other?
how do i create seperate threads for a client to write
and read from a serversocket?Extend java.lang.Thread or implement java.lang.Runnable
and RTFM for both of them. Lots of nice code examples in them thar
API docs.
matfud
Similar Messages
-
Multithreaded problem in read and write thread
This is a producer consumer problem in a multi-threaded environment.
Assume that i have multiple consumer (Multiple read threads) and a
single producer(write thread).
I have a common data structure (say an int variable), being read and written into.
The write to the data sturcture happens occasionally (say at every 2 secs) but read happens contineously.
Since the read operation is contineous and done by multiple threads, making the read method synchronized will add
overhead(i.e read operation by one thread should not block the other read threads). But when ever write happens by
the write thread, that time the read operations should not be allowed.
Any ideas how to achive this ??If all you're doing is reading an int, then just use regular Java synchronization. You'll actually get a performance hit if you're doing simple read operations, as stated in the ReadWriteLock documentation:
Whether or not a read-write lock will improve performance over the use of a mutual exclusion lock depends on the frequency that the data is read compared to being modified, the duration of the read and write operations, and the contention for the data - that is, the number of threads that will try to read or write the data at the same time. For example, a collection that is initially populated with data and thereafter infrequently modified, while being frequently searched (such as a directory of some kind) is an ideal candidate for the use of a read-write lock. However, if updates become frequent then the data spends most of its time being exclusively locked and there is little, if any increase in concurrency. Further, if the read operations are too short the overhead of the read-write lock implementation (which is inherently more complex than a mutual exclusion lock) can dominate the execution cost, particularly as many read-write lock implementations still serialize all threads through a small section of code. Ultimately, only profiling and measurement will establish whether the use of a read-write lock is suitable for your application. -
Can't stop synchronized threads with I/O read and write
I have two synchronized threads which doing read and write from and into a file.
One thread called "reader" which does reading, encoding, etc from a source file and puts its output in a pre-defined variable. Another called "writer" which puts the reader's output into a file ( not the source file ). Both thread will notify each other when they've finished each of their part. It's similiar to CubyHole example of Java Tutorial example from Sun.
But somehow it seems like the threads keep spawning and won't die. Even if the source file has been all read and the data has been fully written, calling interrupt(), return, etc has no effect. The threads will keep running untill System.exit() called.
Is it because the threads were blocked for I/O operation and the only way to kill them is to close the I/O ?
To be honest, it's not only stop the threads that I want to, I also want to somehow pause the threads manually in the middle of the process.
Is it possible ?
Cheers.!!!The example code for the problem using 4 classes called :
- libReadWrite ( class holding methods for aplication operations )
- reader ( thread class responsible for reading data )
- writer ( thread class responsible for writing data )
- myGUI ( user interface class )
All of them written in different file.
// libReadWrite
pubic class libReadWrite {
private boolean dataReady;
private String theData;
//read data
public synchronized void read(String inputFile) {
while (dataReady == true) {
try {
wait();
} catch (InterruptedException ex) {}
RandomAccessFile raf = new RandomAccessFile(inputFile, "r"); // I'm using raf here because there are a lot of seek operations
theData = "whatever"; // final data after several unlist processes
dataReady = true;
notifyAll();
public synchronized void write(String outputFile) {
while (dataReady == false) {
try {
wait();
} catch (InterruptedException ex) {}
DataOutputStream output = new DataOutputStream(new FileOutputStream(outputFile, true));
output.writeBytes(theData);
dataReady = false;
notifyAll();
//Reader
public class reader extends Thread {
private libReadWrite myLib;
private String inputFile;
public reader (libReadWrite myLib, String inputFile) {
this.myLib = myLib;
this.inputFile = inputFile;
public void run() {
while (!isInterrupted()) {
myLib.read(inputFile); <-- this code running within a loop
return;
public class writer extends Thread {
private libReadWrite myLib;
private String outputFile;
public writer (libReadWrite myLib, String outputFile) {
this.myLib = myLib;
this.outputFile = outputFile;
public void run() {
while (!isInterrupted()) {
myLib.write(outputFile); <-- this code running within a loop
try {
sleep(int)(Math.random() + 100);
} catch (InterruptedException ex) {}
return;
//myGUI
public class myGUI extends JFrame {
private libReadWrite lib;
private reader readerRunner;
private writer writerRunner;
//Those private variables initialized when the JFrame open (windowOpened)
libReadWrite lib = new libReadWrite();
reader readerRunner = new reader("inputfile.txt");
writer writerRunner = new writer("outputfile.txt");
//A lot of gui stuffs here but the thing is below. The code is executed from a button actionPerformed
if (button.getText().equals("Run me")) {
readerRunner.start();
writerRunner.start();
button.setText("Stop me");
} else {
readerRunner.interrupt();
writerRunner.interrupt();
} -
Best Practice to Atomic Read and Write a Field In Database
I am from Java Desktop Application background. May I know what is the best practice in J2EE, to atomic read and write a field in database. Currently, here is what I did
// In Servlet.
synchronized(private_static_final_object)
int counter = read_counter_from_database();
counter++;
write_counter_back_to_database(counter);
}However, I suspect the above method will work all the time.
As my observation is that, if I have several web request at the same time, I am executing code within single instance of servlet, using different thread. The above method shall work, as different thread web request, are all referring to same "private_static_final_object"
However, my guess is "single instance of servlet" is not guarantee. As after some time span, the previous instance of servlet may destroy, with another new instance of servlet being created.
I also came across [http://code.google.com/appengine/docs/java/datastore/transactions.html|http://code.google.com/appengine/docs/java/datastore/transactions.html] in JDO. I am not sure whether they are going to solve the problem.
// In Servlet.
Transaction tx = pm.currentTransaction();
tx.begin();
int counter = read_counter_from_database(); // Line 1
counter++; // Line 2
write_counter_back_to_database(counter); // Line 3
tx.commit();Is the code guarantee only when Thread A finish execute Line 1 till Line 3 atomically, only Thread B can continue to execute Line 1 till Line 3 atomically?
As I do not wish the following situation happen.
(1) Thread A read counter from Database as 0
(2) Thread A increment counter to 1
(3) Thread B read counter from Database as 0
(4) Thread A write counter as 1 to database
(5) Thread B increment counter to 1
(6) Thread B write counter as 1 to database
What I wish is
(1) Thread A read counter from Database as 0
(2) Thread A increment counter to 1
(4) Thread A write counter as 1 to database
(3) Thread B read counter from Database as 1
(5) Thread B increment counter to 2
(6) Thread B write counter as 2 to database
Thanks you.
Edited by: yccheok on Oct 27, 2009 8:39 PMThis is my understanding of the issue (you should research it further on you own to get a better understanding):
I suggest you use local variables (ie, defined within a function), and keep away from static variables. Those local variables are thread safe. If you call functions within functions, its still thread safe. If you read or write to one record in a database using sql, its thread safe (you dont need a transaction). If you read/write to multiple tables and/or records, you probably need a transaction. Servlets are thread safe. You usually dont need the 'synchronized' word anywhere unless you have a function updating/reading a static variable and therefore want to ensure only one user is accessing the static varible at a time. Also do so if you are writing to some resource (such as a file, a variable in applicaton scope, session scope, or resource that everyone uses such as email server). You dont want more than one person at a time to write to it). Note the database is one of of those resources that is handled by transactions rather than the the synchronized keyword (the synchronized keyword is applied to your application only (not other applications that someone is running), whereas the transaction ensures all applications are locked out while you update those records in the database).
By the way, if you have a static variable, you should have one and only one function (synchronized) that updates it that everyone uses. If you have more than one synchronized function, that updates it, its probably not thread safe.
An example of a static variable you would use is a Datasource object (to obtain your database connections). You only need one connection pool in your application and you access it via the datasource variable.
If you're unsure your code is thread safe, you can create two seperate threads that call the same block of functions repeatedly to ensure it works as expected. -
I am having EXTREME difficulty trying to establish communications with a Modbus device using LV8.2 shared variables. The device is a Eurotherm 6180XIO Datalogger configured as a Modbus master. The PC and a cFP-1804 are slaves. All IP addresses are set correctly. This approach using shared variables would seem simple, but I can't find any examples or proper guidance on how to get it working. I am trying to avoid having to mess around with TCP/IP, OPC, or any other old-fashioned method.
I have read many threads on related topics but none directly apply to this situation. I have created a library containing a Modbus I/O server and shared variables bound to read and write holding registers. I have followed all recommended tips for creating such variables but I can neither read or write data. All data types are U16 due to Modbus protocol limitations. I have also applied the LV x10 factor in the most significant digit in the register offset (6 digits instead of 5).
I have a cFP-1804 on the same network which reads into the datalogger OK. The registers I use are 31000 (for CH0 on module 0, 31002 for CH1, etc) and the data can be read as FLOAT32. I have updated the firmwate on the 1804 to the latest level. I cannot even get shared variables to read SGL values. Using registers 301001 for CH0 and 301002 for CH1 I can only read U16 values, and not a 2-word SGL.
Third party Modbus simulation software is able to write to and read from registers very easily, but not LabVIEW.
Some questions are:
- do I use a Modbus master or slave as an I/O server in the library as a target for binding the shared variables?
- is there some other wierd translation in register offsets between LabVIEW and traditional Modbus?
- is this actually possible using shared variables or am I wasting my time?Sending the whole 60-character string using a string or array would be the most efficient. I have tried both methods, and these only cause the datalogger to flag a message log but no text is displayed.
For a string variable, I have used the following binding "My Computer\Modbus Test.lvlib\ModbusServer6180\442305", where ModbusServer6180 is a Modbus I/O server configured with the logger IP address, and 42304 is the register offset at the start of the text block in the logger. I need to write to 30 consecutive registers starting with this one. I am not using buffering and have not enabled single writer.
Can anyone confirm whether this method should work in 8.2?
Does the string need a special termination character? -
Help ,ImageIO exception to read and write
Hi,
I'm dynamically creating image files through screens utility of java(prog name:- Test_ScreenShot.java) and saving
them in memory sequentially(pic0.jpg,pic1.jpg....etc).Simultaneously I'm accessing the saved files from another
independent application(Prog name:- Test_Main.java) through piping(executing the application like this "Java
Test_Screens|Java Test_Main").The application is in infinite loop.I'm using Version JDK 1.5
I use java Image to read and write image:-
My application was running well for days.But now I'm getting sudden exceptions.
I got an exception while trying to save an dynamically generated image file in the local memory using the Image
class.In brief I'm getting exactly 3 types of exceptions:-
1)java.io.FileNotFoundException: pic5.jpg (Access is denied)
2)"Exception in thread "main" java.lang.NullPointerException
3)Exception in thread "main" com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
Here is the code snippent I wrote:
/* Robot robot = new Robot();
BufferedImage image = robot.createScreenCapture(screenRect);
// save captured image to jpg file
ImageIO.write(image, "jpg", new File(outFileName));*/
And here is the exception I am finding (I never found this before, I executed the code many times )
=====================================================================================================================
1)Exception Type 1:-
java.io.FileNotFoundException: pic5.jpg (Access is denied)
at java.io.RandomAccessFile.open(Native Method)
at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)
at javax.imageio.stream.FileImageOutputStream.<init>(FileImageOutputStream.java:44)
at com.sun.imageio.spi.FileImageOutputStreamSpi.createOutputStreamInstance(FileImageOutputStreamSpi.java:37)
at javax.imageio.ImageIO.createImageOutputStream(ImageIO.java:391)
at javax.imageio.ImageIO.write(ImageIO.java:1483)
at Test_ScreenShot.main(Test_ScreenShot.java:112)
at Test_Main.main(Test_Main.java:466)
at Test_ScreenShot.main(Test_ScreenShot.java:129)
2)Exception Type 2:-
"Exception in thread "main" java.lang.NullPointerException
at Picture.width(Picture.java:84)
at Test_Edge_Detector.not_main(Test_Edge_Detector.java:38)
at Test_Main.main(Test_Main.java:88)"
============================================================================================
Now I tried the following as alternative of ImageIO(from jdk 1.2)
to read image:-
FileInputStream fis = new FileInputStream(file);
JPEGImageDecoder jpeg = JPEGCodec.createJPEGDecoder(fis);
jpeg.decodeAsBufferedImage();
fis.close();
But after running a long time suddenly its giving following exceptions:-
==============================================================================================
Exception Type 3:- )
Exception in thread "main" com.sun.image.codec.jpeg.ImageFormatException: Not a JPEG file: starts with 0xff 0xd9
at sun.awt.image.codec.JPEGImageDecoderImpl.readJPEGStream(Native Method)
at sun.awt.image.codec.JPEGImageDecoderImpl.decodeAsBufferedImage(Unknown Source)
Exception Type 4:- )
javax.imageio.IIOException: Not a JPEG file: starts with 0xff 0xd9
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readImageHeader(Native Method)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readNativeHeader(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.checkTablesOnly(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.gotoImage(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readHeader(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.readInternal(Unknown Source)
at com.sun.imageio.plugins.jpeg.JPEGImageReader.read(Unknown Source)
at javax.imageio.ImageIO.read(Unknown Source)
at javax.imageio.ImageIO.read(Unknown Source)
at Picture.<init>(Picture.java:22)
at Test_Edge_Detector.not_main(Test_Edge_Detector.java:37)
at Test_Main.main(Test_Main.java:88)
Exception in thread "main" java.lang.RuntimeException: Could not open file: pic45.jpg
at Picture.<init>(Picture.java:27)
at Test_Edge_Detector.not_main(Test_Edge_Detector.java:37)
at Test_Main.main(Test_Main.java:88)
My question is:-
1)Where is the actual problem?Is it any kind of bug?
2)I'm using the concept of piping recently to execute the application.Can it be the cause?
When I googled I found the following informations.There is a bug in ImageIO while trying to write image file.But
I'm not sure about that it will be relevent here :-
1)from sun's bug database:-
http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6247985
2)from SUN Developer Forums
http://forum.java.sun.com/thread.jspa?threadID=768917&messageID=4382833
3)from Java.NET forum(here they r getting the bug while they r using createScreenCapture() method of robot class,I am
also using that in my code)
http://forums.java.net/jive/thread.jspa?messageID=123247
4)from SUN's archieve
http://archives.java.sun.com/cgi-bin/wa?A2=ind0207&L=java-imageio-interest&D=0&P=1483
5)Here is the actual implemetation of ImageIO class.I'm getting error at 391 no. line.
http://kickjava.com/src/javax/imageio/ImageIO.java.htm
Thanks And Regards
SubhadipHello,
I am writng to ask a doubt I have been encountered. I have an array of Image URL's and I am downloading the images using thses URL for each index. The example for an image URL will be as follows:
http://www.firstmonday.org/issues/issue6_10/wiggins/google-3oct2001.gifIf the URL is abroken link, I am getting the exception. But if the URL is somewhat hanging (which means when u open that URL in IE or Mozilla, the statuc bar for downloading the image will be hanging).
So i want to set a timer for every link while downloading. may be 10min. My idea is if in that 10min, if code does not completes downloading the images, then ignore that link and proceed furthur.
Can u please tell me how to write this.. Please tell me any other idea to tackle this problem.
Thank you,
Chaitanya -
Which is better? To wire a URL or a reference into Datasocket read/write?
Does wiring in the reference save processor effort/time? Do I have to close the DS reference before I can do other things to either the same DS connection or other connections? The examples I have looked at tend to use URL's, why is this?
(I am running Labview 7.0 on Windows 2000)I'd like to bring this thread back up because I'm having the same issue as Michael here.....
I'm stumped on a the functionality of the Read/Write mode for the Datasockets Open VI.
I've attached a picture below showing the 2 different methods of
opening Datasocket references....In one case, I use the Read/Write mode
for DS open, in the other case, I use 2 DS opens: One for READ and
another for WRITE. For some reason, only the latter program works
properly (when I open READ and WRITE separately). Why is this?
I
thought that if the READ/WRITE MODE was used, the output reference can
be used with the Datasocket READ and Datasocket WRITE Vi's as shown in
Top Vi of picture. Instead, It seems I'm unable to "change" the state
of the Datasocket tag using the the Top Vi.
FYI: I'm using
DS server manager to create the item. I've also gave proper privileges
to each computer so that they can communicate with the DS server. It
obviously works since using the bottom VI, I get the desired results.
What am i doing wrong? Are my expectations for the Rea/dWrite functionality correct?
Message Edited by RegisPhilbin on 07-15-2005 11:11 AM -
How do I read and write at the same time using the NI-CAN channel API?
Here's the situation. I have one CAN bus, and I need to read and write channel data (using the channel API) at the same time both at an interval of 20 ms. It's easy to do one or the other using the channel API, but you can't setup a channel task to do both. It's either input or output, not both. Is this even possible?
Hi,
yes , this is possible. But you have to create two tasks, one for input and one for output. see the attached example for LabVIEW.
If you download and install NI-CAN 2.4 you will get this example and one for C and VB as well.
DirkW
Attachments:
Single Sample Input Output same Port.vi 79 KB -
How do I read and write to text files on a remote computer's hard drive
I would like to read and write data to a text file on a remote computer. This is easily accomplished using one of the file functions such as "write characters to file.vi". If I am already connected to the remote computer, all I need to do is specify the path to the particular file and it will work fine.
My problem is that I want to connect to the remote computer programatically within LabVIEW (I do not want to have to use the computer's OS to establish the connection. Is there a function that I can use to do this?
Thomas D. Schaefer
Wells Manufacturing CorpYariv,
You should really start a new thread with a new question like this, so that more people see it. Some people look primarily at threads that have no responses yet. Also, don't post the exact same question in multiple places. Or, if you must cross-post to some other forum, make sure to mention it in your question text.
I'm happy to be a brick in your Western Wall, but I'm not sure what the main objective is here. Is the main problem really getting access to the "X bytes received in Y seconds at Z bytes/sec" string? Or is it accomplishing the file transfer? And what OS and LabVIEW version are you running?
I think your problem is that you the LabVIEW System Exec command does not allow for the degree of interactivity that you need if you want to issue a sequence of commands to a command-line executable. However, under Windows XP (and, presumably, other Windows versions, though I can't check), you can tell the FTP executable to use commands from a textfile script by using the -s switch, and you can override the prompts during multiple file transfers with the -i switch:
ftp -i -s:FILEPATH SERVERNAME
If you issue a command in this format to System Exec, and make sure to create a file at FILEPATH with your command sequence (one per line), then you should at least accomplish the FTP actions. This won't give you the transfer details in the standard output, unfortunately. However, if you just want a general sense of how much was transferred and how quickly it happened, you can code that in LabVIEW by getting the resulting file sizes and using Tick Count before and after the System Exec call to see how long the transfer took.
Hope that helps,
John -
Why does this class not read and write at same time???
I had another thread where i was trying to combine two class files together
http://forum.java.sun.com/thread.jspa?threadID=5146796
I managed to do it myself but when i run the file it does not work right. If i write a file then try and open the file it says there are no records in the file, but if i close the gui down and open the file everything get read in as normal can anybody tell me why?
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import bank.BankUI;
import bank.*;
public class testing extends JFrame {
private ObjectOutputStream output;
private BankUI userInterface;
private JButton SaveToFile, SaveAs, Exit; //////////savetofile also saves to store need to split up and have 2 buttons
//private Store store; MIGHT BE SOMETHING TO DO WITH THIS AS I HAD TO COMMENT THIS STORE OUT TO GET IT WORKING AS STORE IS USED BELOW
private Employee record;
//////////////////////////////////////from read
private ObjectInputStream input;
private JButton nextButton, openButton, nextRecordButton ;
private Store store = new Store(100);
private Employee employeeList[] = new Employee[100];
private int count = 0, next = 0;
/////////////////////////////////////////////from read end
// set up GUI
public testing()
super( "Employee Data" ); // appears in top of gui
// create instance of reusable user interface
userInterface = new BankUI( 9 ); // nine textfields
getContentPane().add( userInterface, BorderLayout.CENTER );
// configure button doTask1 for use in this program
SaveAs = userInterface.getSaveAsButton();
SaveAs.setText( "Save as.." );
//////////////////from read
openButton = userInterface.getOpenFileButton();
openButton.setText( "Open File" );
openButton.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// close file and terminate application
public void actionPerformed( ActionEvent event )
openFile();
} // end anonymous inner class
); // end call to addActionListener
// register window listener for window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// close file and terminate application
public void windowClosing( WindowEvent event )
if ( input != null )
closeFile();
System.exit( 0 );
} // end anonymous inner class
); // end call to addWindowListener
// get reference to generic task button doTask2 from BankUI
nextButton = userInterface.getDoTask2Button();
nextButton.setText( "Next Record" );
nextButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
readRecord();
} // end anonymous inner class
); // end call to addActionListener
//get reference to generic task button do Task3 from BankUI
// get reference to generic task button doTask3 from BankUI
nextRecordButton = userInterface.getDoTask3Button();
nextRecordButton.setText( "Get Next Record" );
nextRecordButton.setEnabled( false );
// register listener to call readRecord when button pressed
nextRecordButton.addActionListener(
// anonymous inner class to handle nextRecord event
new ActionListener() {
// call readRecord when user clicks nextRecord
public void actionPerformed( ActionEvent event )
getNextRecord();
} // end anonymous inner class
); // end call to addActionListener
///////////from read end
// register listener to call openFile when button pressed
SaveAs.addActionListener(
// anonymous inner class to handle openButton event
new ActionListener() {
// call openFile when button pressed
public void actionPerformed( ActionEvent event )
SaveLocation();
} // end anonymous inner class
); // end call to addActionListener
// configure button doTask2 for use in this program
SaveToFile = userInterface.getSaveStoreToFileButton();
SaveToFile.setText( "Save to store and to file need to split this task up" );
SaveToFile.setEnabled( false ); // disable button
// register listener to call addRecord when button pressed
SaveToFile.addActionListener(
// anonymous inner class to handle enterButton event
new ActionListener() {
// call addRecord when button pressed
public void actionPerformed( ActionEvent event )
addRecord(); // NEED TO SPLIT UP SO DONT DO BOTH
} // end anonymous inner class
); // end call to addActionListener
Exit = userInterface.getExitAndSaveButton();
Exit.setText( "Exit " );
Exit.setEnabled( false ); // disable button
// register listener to call addRecord when button pressed
Exit.addActionListener(
// anonymous inner class to handle enterButton event
new ActionListener() {
// call addRecord when button pressed
public void actionPerformed( ActionEvent event )
addRecord(); // adds record to to file
closeFile(); // closes everything
} // end anonymous inner class
); // end call to addActionListener
// register window listener to handle window closing event
addWindowListener(
// anonymous inner class to handle windowClosing event
new WindowAdapter() {
// add current record in GUI to file, then close file
public void windowClosing( WindowEvent event )
if ( output != null )
addRecord();
closeFile();
} // end anonymous inner class
); // end call to addWindowListener
setSize( 600, 500 );
setVisible( true );
store = new Store(100);
} // end CreateSequentialFile constructor
// allow user to specify file name
////////////////from read
// enable user to select file to open
private void openFile()
// display file dialog so user can select file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showOpenDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
// obtain selected file
File fileName = fileChooser.getSelectedFile();
// display error if file name invalid
if ( fileName == null || fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
input = new ObjectInputStream(
new FileInputStream( fileName ) );
openButton.setEnabled( false );
nextButton.setEnabled( true );
// process exceptions opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error Opening File",
"Error", JOptionPane.ERROR_MESSAGE );
} // end else
} // end method openFile
public void readRecord() // need to merger with next record
Employee record;
// input the values from the file
try {
record = ( Employee ) input.readObject();
employeeList[count++]= record;
store.add(record);/////////ADDS record to Store
store.displayAll();
System.out.println("Count is " + store.getCount());
// create array of Strings to display in GUI
String values[] = {
String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getDateOfBirth()),
String.valueOf( record.getID()),
String.valueOf( record.getStartDate()),
String.valueOf( record.getSalary()),
String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone())
// i added all those bits above split onto one line to look neater
// display record contents
userInterface.setFieldValues( values );
// display message when end-of-file reached
catch ( EOFException endOfFileException ) {
nextButton.setEnabled( false );
nextRecordButton.setEnabled( true );
JOptionPane.showMessageDialog( this, "No more records in file",
"End of File", JOptionPane.ERROR_MESSAGE );
// display error message if class is not found
catch ( ClassNotFoundException classNotFoundException ) {
JOptionPane.showMessageDialog( this, "Unable to create object",
"Class Not Found", JOptionPane.ERROR_MESSAGE );
// display error message if cannot read due to problem with file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this,
"Error during read from file",
"Read Error", JOptionPane.ERROR_MESSAGE );
} // end method readRecord
private void getNextRecord()
Employee record = employeeList[next++%count];//cycles throught accounts
//create aray of string to display in GUI
String values[] = {String.valueOf(record.getName()),
String.valueOf(record.getGender()),
String.valueOf( record.getStartDate() ), String.valueOf( record.getAddress()),
String.valueOf( record.getNatInsNo()),
String.valueOf( record.getPhone()),
String.valueOf( record.getID() ),
String.valueOf( record.getDateOfBirth() ),
String.valueOf( record.getSalary() ) };
//display record contents
userInterface.setFieldValues(values);
//display record content
///////////////////////////////////from read end
private void SaveLocation()
// display file dialog, so user can choose file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode( JFileChooser.FILES_ONLY );
int result = fileChooser.showSaveDialog( this );
// if user clicked Cancel button on dialog, return
if ( result == JFileChooser.CANCEL_OPTION )
return;
File fileName = fileChooser.getSelectedFile(); // get selected file
// display error if invalid
if ( fileName == null || fileName.getName().equals( "" ) )
JOptionPane.showMessageDialog( this, "Invalid File Name",
"Invalid File Name", JOptionPane.ERROR_MESSAGE );
else {
// open file
try {
output = new ObjectOutputStream(
new FileOutputStream( fileName ) );
SaveAs.setEnabled( false );
SaveToFile.setEnabled( true );
Exit.setEnabled( true );
// process exceptions from opening file
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error Opening File",
"Error", JOptionPane.ERROR_MESSAGE );
} // end else
} // end method openFile
// close file and terminate application
private void closeFile()
// close file
try {
//you want to cycle through each recordand add them to store here.
int storeSize = store.getCount();
for (int i = 0; i<storeSize;i++)
output.writeObject(store.elementAt(i));
output.close();
input.close();// from read!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
System.exit( 0 );
// process exceptions from closing file
catch( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error closing file",
"Error", JOptionPane.ERROR_MESSAGE );
System.exit( 1 );
} // end method closeFile
// add record to file
public void addRecord()
int employeeNumber = 0;
String fieldValues[] = userInterface.getFieldValues();
// if account field value is not empty
if ( ! fieldValues[ BankUI.IDNUMBER ].equals( "" ) ) {
// output values to file
try {
employeeNumber = Integer.parseInt(
fieldValues[ BankUI.IDNUMBER ] );
String dob = fieldValues[ BankUI.DOB ];
String[] dateofBirth = dob.split ("-"); // what used to put between number chnage to /
String sDate = fieldValues[ BankUI.START ];
String[] startDate = sDate.split ("-");
String sex = fieldValues[ BankUI.GENDER ];
char gender = (sex.charAt(0)); // check if m or f prob check in employee
if ( employeeNumber >= 0 ) {
/* create new record =String name, char gender, Date dob, String add, String nin, String phone, String id, Date start, float salary*/
record = new Employee(
fieldValues[ BankUI.NAME ],
gender,
new Date( Integer.parseInt(dateofBirth[0]),
Integer.parseInt(dateofBirth[1]),
Integer.parseInt(dateofBirth[2])),
fieldValues[ BankUI.ADDRESS ],
fieldValues[ BankUI.NATINTNO ],
fieldValues[ BankUI.PHONE ],
fieldValues[ BankUI.IDNUMBER ],
new Date( Integer.parseInt(startDate[0]),
Integer.parseInt(startDate[1]),
Integer.parseInt(startDate[2])),
Float.parseFloat( fieldValues[ BankUI.SALARY ] ));
if (!store.isFull())
store.add(record);
else
JOptionPane.showMessageDialog( this, "The Store is full you cannot add\n"+
"anymore employees. \nPlease Save Current File and Create a New File." );
System.out.println("Store full");
store.displayAll();
System.out.println("Count is " + store.getCount());
// output record and flush buffer
//output.writeObject( record );
output.flush();
else
JOptionPane.showMessageDialog( this,
"Account number must be greater than 0",
"Bad account number", JOptionPane.ERROR_MESSAGE );
// clear textfields
userInterface.clearFields();
} // end try
// process invalid account number or balance format
catch ( NumberFormatException formatException ) {
JOptionPane.showMessageDialog( this,
"Bad ID number, Date or Salary", "Invalid Number Format",
JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( ArrayIndexOutOfBoundsException ArrayException ) {
JOptionPane.showMessageDialog( this, "Error with Start Date or Date of Birth\nPlease enter like: 01-01-2001",
"IO Exception", JOptionPane.ERROR_MESSAGE );
// process exceptions from file output
catch ( IOException ioException ) {
JOptionPane.showMessageDialog( this, "Error writing to file",
"IO Exception", JOptionPane.ERROR_MESSAGE );
closeFile();
} // end if
} // end method addRecord
public static void main( String args[] )
new testing();
} // end class CreateSequentialFileSure you can read and write at the same time. But normally you would be reading from one place and writing to another place.
I rather regret avoiding the OP's earlier post asking how to combine two classes. I looked at the two classes posted and realized the best thing to do was actually to break them into more classes. But I also realized it was going to be a big job explaining why and how, and I just don't have the patience for that sort of thing.
So now we have a Big Ball Of Tar™ and I feel partly responsible. -
How many ways to read and write a local variable in a called VI?
Ciao!
I'm producing my first TestStand sequence. It is called "FirstAttempt" and it is made by a single step which calls a VI. One of the first dilemmas i encountered realizing this sequence is how to read and write a local variable (created going in Variables -> Locals ('FirstAttempt') -> <right click to insert local>) in the called VI.
The first way (the only one i tried) is to create a control and an indicator on the VI front panel, connect them to their respective terminals in the connector pane and then specify (going in Step Settings -> Module) that these connectors (shown in the Parameter Name column) are linked to the local variable (selected in the Value column).
The second way (not tried) consists in using TestStand API: create a Sequence Context reference on the VI front panel, link it to a property node in the block diagram, select the property "Locals" and extract from this the local variable name and value which, i think, can be readable and writable.
So...
Are the shown ways correct?
Are there other ways?
Knowing that a "local" variable can be considered "global" within the whole sequence, is there the possibility to simply create a reference to the local variable and use the reference in the called VI block diagram in order to save space in the connector pane (if using method 1) or in the block diagram (if using method 2)?
Thanks!
Message Edited by aRCo on 09-17-2009 05:09 AMHi,
Before TestStand 3 you would use the second way you quoted as its the only way.
But now you would use the first way you quoted. You may still what to pass the SequenceContext if you were going to use the TestStand API. For TestStand 3.x and above you would use this way as the first chose. (Personnelly, I would not pass the SequenceContext into a VI if I know it was never going to be used in that VI.)
Not sure I understand your final comment, maybe you are liking it to passing the reference of a control to a subVI so that the control can be updated from within the subVI.
If this is the case and you had a situation where you had a step that was running in parallel with the rest of the steps in the sequence either as a separate thread or execution and were dependent on the contents of the local variable changing from that parallel running step, then you would have to use the API SetVal method to change the local.
Hope this is clear.
Regards
Ray Farmer
Regards
Ray Farmer -
I am running FF 18.0.2 on a Win7 system with an i7 CPU and 8GB RAM. My Flash plugin is newly-updated. I've used Firefox on this machine its entire life (3 years).
Since 3 or 4 (?) versions ago, I've been getting massive activity on my hard drive with Firefox. When I check with Win Task Manager, I see the plugin-container.exe *32 and the FlashPlayerPlugin_11_5_502_149.exe *32 processes are generating millions of I/O reads and writes, even while Firefox is idle (minimized, running no audio or video). On this latest version, 18.0.2, the drive activity stalls out YouTube videos repeatedly, even though I can see they're buffered ahead. The playing video will stop, audio will continue to end of buffer, and then EVERYTHING stops (Firefox not responding) for 30 seconds or so. It will then pickup again and play until it repeats the same pattern in a minute or so.
Example: I closed and restarted Firefox 2 days ago. Earlier today I checked Windows Task Manager and found the two processes EACH generated about 161 million reads and 141 million writes since then! My wife's laptop is showing nothing like a hundredth of that.
The constant drive activity is slowing down all programs outside of Firefox too, as you might imagine. The PC is acting like it's a dedicated machine for Flash.The Reset Firefox feature can fix many issues by restoring Firefox to its factory default state while saving your essential information.
Note: ''This will cause you to lose any Extensions, Open websites, and some Preferences.''
To Reset Firefox do the following:
#Go to Firefox > Help > Troubleshooting Information.
#Click the "Reset Firefox" button.
#Firefox will close and reset. After Firefox is done, it will show a window with the information that is imported. Click Finish.
#Firefox will open with all factory defaults applied.
Further information can be found in the [[Reset Firefox – easily fix most problems]] article.
Did this fix your problems? Please report back to us! -
Windows 2008 R2 Folder assign permission "Read and Write" problem with *.doc file
Hello All,
I am a new one here,
I am sorry for any mistakes and also my english is so poor.
M Brother company runing Windows 2008 R2 as Active Directory...
We have folder Name: Admin
and in this folder, there are alot documents files as : *.doc, *.dwg, *.txt etc.....
All user accesing to these files and they can open to edit and save...
One day my brother want me to set Admin folder for all users just"Read and Write.." mean they still can open files to edit and save... but can't delete..
I did success with this..
But only one thing happen.. when they open *.doc file to edit and attempting to save, the message alert" access denide " and they can only "SAVE AS"...We don't want "Save as"
Could you show me how can we fix error with *.doc file while they trying to save? because it allow only save as.. but other files as *.text file or *.dwg they can save without problem..
Could expert here ever face this issues and fix by yourself, please share me with this..
Please help me..
Best regards,Hi,
Office programs are specific. They will create a temp file when edit, then the temp file will be deleted when close. So Delete permission is needed for users to saving Office files like Excel/Word.
For more detaile information, please refer to the thread below:
Special Permissions - User cannot save files
http://social.technet.microsoft.com/Forums/windowsserver/en-US/721fb2f1-205b-46e5-a3dc-3029e5df9b5b/special-permissions-user-cannot-save-files
Best Regards,
Mandy
Please remember to mark the replies as answers if they help and unmark them if they provide no help. If you have feedback for TechNet Subscriber Support, contact [email protected] -
File Read and Write using File Adapter in Bpel
In Bpel Process i am using File Adapter ( Schema is Opaque) for read and write the file contents. i am able do successful deployment and read, write function in first time deployment, after that again i tired to run the application, its not going to write the content of file, its only writing the file with out data's or content in that file.
Please help me...
SaravananHi Eric
In my domain.log file having the following details. In this file im unable to find out what the exact problem. Please look at this and help me.
<2008-01-22 18:25:42,024> <INFO> <default.collaxa.cube.compiler> validating "C:\product\10.1.3.1\OracleAS_1\bpel\domains\default\tmp\.bpel_BPELProcess2_1.1_298e83988d77b6640c33dfeec11ed31b.tmp\BPELProcess2.bpel" ...
<2008-01-22 18:25:49,850> <INFO> <default.collaxa.cube.engine.deployment> <CubeProcessFactory::generateProcessClass>
Process "BPELProcess2" (revision "1.1") successfully compiled.
<2008-01-22 18:25:49,914> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Loading JCAActivationAgent for {portType=Read_ptt}
<2008-01-22 18:25:49,914> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::load - Locating Adapter Framework instance: OraBPEL
<2008-01-22 18:25:49,930> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::load - Done loading JCAActivationAgent for processId='bpel://localhost/default/BPELProcess2~1.1/
<2008-01-22 18:25:49,930> <INFO> <default.collaxa.cube.engine.deployment> Process "BPELProcess2" (revision "1.1") successfully loaded.
<2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::uninit Shutting down the JCA activation agent, processId='bpel://localhost/default/BPELProcess2~1.0/', activation properties={portType=Read_ptt}
<2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Adapter Framework instance: OraBPEL - performing endpointDeactivation for portType=Read_ptt, operation=Read
<2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> Endpoint De-activation called in adapter for endpoint : D:\MAXIMUS_Project_Softwares\jdevstudiobase10132\jdev\mywork\MyLabs\BPELProcess2\in
<2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::init - Initializing the JCA activation agent, processId='bpel://localhost/default/BPELProcess2~1.1/
<2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> JCAActivationAgent::initiateInboundJcaEndpoint - Creating and initializing inbound JCA endpoint for:
process='bpel://localhost/default/BPELProcess2~1.1/'
domain='default'
WSDL location='rd.wsdl'
portType='Read_ptt'
operation='Read'
activation properties={portType=Read_ptt}
<2008-01-22 18:26:02,698> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Adapter Framework instance: OraBPEL - endpointActivation for portType=Read_ptt, operation=Read
<2008-01-22 18:26:02,730> <INFO> <default.collaxa.cube.activation> <File Adapter::Inbound> Endpoint Activation called in File Adapter for endpoint: D:\MAXIMUS_Project_Softwares\jdevstudiobase10132\jdev\mywork\MyLabs\BPELProcess2\in
<2008-01-22 18:26:02,730> <INFO> <default.collaxa.cube.activation> <AdapterFramework::Inbound> Adapter Framework instance: OraBPEL - successfully completed endpointActivation for portType=Read_ptt, operation=Read
<2008-01-22 18:26:02,890> <WARN> <default.collaxa.cube.activation> <File Adapter::Inbound> PollWork::run exiting, Worker thread will die
<2008-01-22 18:26:04,171> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> Managed Connection Created
<2008-01-22 18:26:04,171> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> Connection Created
<2008-01-22 18:26:04,171> <INFO> <default.collaxa.cube.ws> <File Adapter::Outbound> FileInteraction Created -
Instrument i/o assistant always generates async methods for read and write!
I am trying to generate VI by instrument i/o assistant, but it generated 'Visa write' and 'Visa read' always in asynchronous mode. Even if I unchecked asynch boxes in MAX->Visa Test Panel.
I need only synchronous mode! And it is very uncovenient after open front panel change Synchronous I/O Mode from Asynchronous to Synchronous!postoroniy_v wrote:
Asynchronous mode does not work for my hardware.
and before Instrument i/o assistant generate diagram I have possibility to check requests and responses to/from my hardware. in this case everything is fine.
after generate does not work.
Is it possible you don't have a sufficient amount of wait time between a VISA Write and VISA read to give the instrument time to receive the communication and turn around a response? Take a look at Basic Serial Read and Write example VI. If you are using the I/O assistant and checking things manually, it will work because there is no way you can generate a Read too fast. It still would take a fraction of second to generate the write and do whatever clicking to generate the read.
Maybe you are looking for
-
My Pre doesn't display text of incoming mail mesages
Hi, in the last few days I noticed that the mail program of my Palm Pre doesn't display any plain text of the incoming messages. It normally connects to mail server and load messages, attachements are displayed and open as usual but no text can be vi
-
Should I upgrade to 4.11 or not?
New mini. Clean install just done. Combo pack here ready to go, tested before the clean re-install. No probs. But all in all, is the .11 upgrade worthy? All I know is many websites get screwed on Safari3, while they're nice on Safari2.x Suggestions w
-
How can i recover my rescue email
pls. help me to rescue my security question or rescue email so i can purchase on apple store i already redeem 15 usd and put the code but suddenly they are asking for the security question i already forget my answer on that and i cannot remember my r
-
How to consume SOAP service in Agentry?
Hello, I am new in Agentry and I want to consume .asmx service in agentry.for that can I do changes in work manager or I have to create new project.what I have to do please guide me for the same.I am using Eclipse with agentry plugins and WM
-
Error in accessing the visual composer
I am just trying to access the VC from the portal url. I am getting the following error. Visual Composer - Permission denied Roles specification: You don't have a Visual Composer role. Contact your administrator to get help What role need to add to m