Reading in a loop
First, I want to thank all of you who answered to any of my questions, I appreciate it and it helps me to progress a lot. My actual question is about reading in a loop. I read a string (Visa read) of a specified lenght of bytes from my serial port. This visa read is in a while loop, and I'd like to cummulate all the readings in a text indicator (and eventually in a file). For now, I'm only able to get the last reading, 'cause if I put my text indicator in the loop, it overwrites at each iteration and if I put it outside, it keeps only the last reading. I'm sure it's just about concatenating or building text but I did not find how. Thanks once again for help.
Philippe
Right click on the border of your loop and create a shift register. Once you have created this concatentate the strings together. You can then place an indicator in the loop and see previous iterations data. Look in the help to explain shift registers alittle better. Hope this helps.
BJD1613
Lead Test Tools Development Engineer
Philips Respironics
Certified LV Architect / Instructor
Similar Messages
-
Dear All,
Please let me know which one of the two should I use to improve the performance, for tables containing a lot of data ?
Regards,
Thanks in anticipation.
Alok.Hi,
Follow below steps.
In se30 transaction you can look for
Tip&TRicks button on application toolbar
apart from below conventions
Follow below steps
1) Remove corresponding from select satement
2) Remove * from select
3) Select field in sequence as defined in database
4) Avoid unnecessary selects
i.e check for internal table not initial
5) Use all entries and sort table by key fields
6) Remove selects ferom loop and use binary search
7) Try to use secondary index when you don't have
full key.
8) Modify internal table use transporting option
9) Avoid nested loop . Use read table and loop at itab
from sy-tabix statement.
10) free intrenal table memory wnen table is not
required for further processing.
11)
Follow below logic.
FORM SUB_SELECTION_AUFKTAB.
if not it_plant[] is initial.
it_plant1[] = it_plant[].
sort it_plant1 by werks.
delete adjacent duplicates from it_plant1 comparing werks
SELECT AUFNR KTEXT USER4 OBJNR INTO CORRESPONDING FIELDS OF TABLE I_AUFKTAB
FROM AUFK
FOR ALL ENTRIES IN it_plant1
WHERE AUFNR IN S_AUFNR AND
KTEXT IN S_KTEXT AND
WERKS IN S_WERKS AND
AUART IN S_AUART AND
USER4 IN S_USER4 AND
werks eq it_plant1-werks.
free it_plant1.
Endif.
ENDFORM. "SUB_SELECTION_AUFKTAB
Regards
Amole -
I am acquiring data from a DAQ e series card. i intialized the daq by using AI config out side while loop . i used AI start and AI read in while loop . iam acquiring data from 5 channels. the buffer size ia 1000 and so is the scan rate in AI start.I want to save the acquired data in the file. i am also displaying data o n chart. every thing is working fine. my problem is i want to save 500 points in one seconds. for this i changed the while loop execution time by using waint until multiple sec VI and assign it 10 i was expecting that now iwll save more data point in file as now loop will execute more fast but it does not happen like this. is there any way to minimize the executing time of whil loop.i checked if i deleted AI start and AI read then loop execute very very quickly. should i place AI start and AI read out side loop but then how will it acquire data contiously. I m attaching gif file of the protion of my VI .any suggestion?
Attachments:
myVi.GIF 72 KBI was working quickly, and from memory, so my apologies for errors or non-clarity in my previous post. :-(
The AI START VI, should be used OUTSIDE the loop, since you only want to START the task ONCE.
When the task is complete (your WHILE loop is done), then call the AI CLEAR task to clean up (ONCE).
If you set the NUMBER OF SCANS TO ACQUIRE input to AI START to zero, that has a special meaning: acquire data indefinitely. It will not stop on it's own (assuming no errors occur), you have to explicitly stop it.
If you do this, you have to read the data often enough to avoid buffer overflow, which means the incoming data is filling up the buffer faster than you're emptying it.
I have attached a picture of the general idea. If you really want to use the CPU efficiently, then consider the shift-register idea in the picture - you process on batch of data WHILE the next batch is coming in. If you want a simpler solution, forget the shift-reg, and process it directly after reading it. If your buffer is twice the size of your processing size, you'll be OK.
Message Edited by CoastalMaineBird on 09-14-2005 07:45 PM
Steve Bird
Culverson Software - Elegant software that is a pleasure to use.
Culverson.com
Blog for (mostly LabVIEW) programmers: Tips And Tricks
Attachments:
DAQExample.png 16 KB -
I pull fiftyfour bytes of data from MicroProcessor's EEPROM using serial port. It works fine. I then send a request for 512 bytes and my "read" goes into loop condition, no bytes are delivered and system is lost
Hello,
You mention that you send a string to the microprocessor that tells it how many bytes to send. Instead of requesting 512 bytes, try reading 10 times and only requesting about 50 bytes at a time.
If that doesn�t help, try directly communicating with your microprocessor through HyperTerminal. If you are not on a Windows system, please let me know. Also, if you are using an NI serial board instead of your computer�s serial port, let me know.
In Windows XP, go to Start, Programs, Accessories, Communications, and select HyperTerminal.
Enter a name for the connection and click OK.
In the next pop-up dialog, choose the COM port you are using to communicate with your device and click OK.
In the final pop
-up dialog, set the communication settings for communicating with your device.
Type the same commands you sent through LabVIEW and observe if you can receive the first 54 bytes you mention. Also observe if data is returned from your 512 byte request or if HyperTerminal just waits.
If you do not receive the 512 byte request through HyperTerminal, your microprocessor is unable to communicate with your computer at a low level. LabVIEW uses the same Windows DLLs as HyperTerminal for serial communication. Double check the instrument user manual for any additional information that may be necessary to communicate.
Please let me know the results from the above test in HyperTerminal. We can then proceed from there.
Grant M.
National Instruments -
Hi EXpert,
I have an internal table say itab and I need to fetch a single record with some given conditions.
Hence I have used READ table statement ,
But on using this read table statement , I am unable to fetch the record :-(((( . It gives sy-subrc = 4.
And the same conditions when are put in Loop at itab statement, then I am able to fetch the data .
My requirement is only 1 record for the given conditions ( in where clause in case of loop at statement).
I think I am probably missing out on some minor thing..
<removed_by_moderator>
Warm Regards,
SUDHA
Edited by: Julius Bussche on Feb 7, 2009 2:48 PMHi,
Test the following Code hope it will solve out your problem,
PARAMETERS: key TYPE i .
TYPES: BEGIN OF t_test,
s_no TYPE i,
name(15),
END OF t_test.
DATA: it_test TYPE STANDARD TABLE OF t_test WITH HEADER LINE.
DO 10 TIMES.
it_test-s_no = sy-index.
it_test-name = 'SDN'.
APPEND it_test TO it_test.
ENDDO.
READ TABLE it_test INTO it_test WITH KEY key.
IF sy-subrc = 0.
WRITE: 'sy-subrc = ' , sy-subrc,
/1 it_test-s_no, 15 it_test-name.
ELSE.
WRITE: 'sy-subrc = ' , sy-subrc,
/ 'Sorry there is no Records with this Key'.
ENDIF.
Kind Regards,
Faisal
Edited by: Faisal Altaf on Feb 7, 2009 6:59 PM -
Working with LV 8.2.1 real-time to develop a host of applications that monitor or emulate computers on RS-422 busses. The following screen shots were taken from an application that monitors a 200Hz transmission. After a few hours, the PXI station would crash with an awesome array of angry messages...most implying something about a loss of memory. After much hair pulling and passing of the buck, my associate was able to discover while watching the available memory on the controller that memory loss was occurring with every loop containing a VISA read and error propogation using the data nodes (see Memory Leak.jpg). He found that if he switched the error propogation to regular old-fashioned shift registers, then the available memory was rock-solid. (a la No Memory Leak.jpg)
Any ideas what could be causing this? Do you see any problems with the way we code these sorts of loops? We are always attempting to optimize the way we use memory on our time-critical applications and VISA reads and DAQmx Reads give us the most heartache as we are never able to preallocate memory for these VIs. Any tips?
Dan Marlow
GDLS
Solved!
Go to Solution.
Attachments:
Memory Leak.JPG 136 KB
No Memory Leak.JPG 137 KBHi thisisnotadream,
This problem has been reported, and you seem to be exactly reproducing the conditions required to see this problem. This was reported to R&D (# 134314) for further investigation. There are multiple possible workarounds, one of which is the one that you have already found of wiring the error directly into the loop. Other situations that result in no memory leak are:
1. If the bytes at port property node is not there and a read just happens in every iteration and resulting timeouts are ignored.
2. If the case structure is gone and just blindly check the bytes at port and read every iteration.
3. If the Timed Loop is turned into a While loop.
Thanks for the feedback!
Regards,Stephen S.
National Instruments
Applications Engineering -
How To Pass A Value Read By A Loop To Main Method
Hey everybody,
I'm at this with my code.I'm reading the values of a text file in a loop.I want to pass these values to main method.The importhant point is I want to do this without using a field. The code is below. Thanks.
//Main
public static void main(String[] args)throws FileNotFoundException
DoubleClass AvgScore=new DoubleClass();
IntClass Messenger=new IntClass();
PrintWriter writer1=new PrintWriter("D:\\JavaExercises\\CH07EX14out.txt");
Scanner scan1=new Scanner(new FileReader("D:\\JavaExercises\\CH07EX14data.txt"));
//1 ogrencinin notlarini okut ve ortalamasını hesaplat
while(scan1.hasNext())
writer1.print(scan1.next()+" ");
calcAvg(AvgScore,scan1,Messenger);
//AvgScore formatlanarak yazdirilacak
writer1.print(""+AvgScore+" ");
writer1.print(""+calcGrade(AvgScore)+"\n");
writer1.close();
//calcAvg
public static void calcAvg(DoubleClass x,Scanner y,IntClass z)
int counter=0;
double TotalScore=0;
int NumTests=1;
int Score=0;
//Bir ogrenci icin toplam notu ve test sayisini bul.
while(counter<=4)
Score=y.nextInt();
TotalScore+=Score;
counter++;
NumTests++;
//Bir ogrenci icin not ortalamsi bul.
x.setNum(TotalScore/NumTests);
}Malkavian187 wrote:
Guys please pay attention,
I already said I can't use a field(class scoped variable)and can't use a return type method.
I ve heard that it can be done by passing a reference or primitive variable to my calcAvg method.And than assignin the read values back to this variable.
But I can't figure out how to make it. I need a complete solution.Including modifications to calcAvg and main method.
Take care,Malkavian187,
Maybe you haven't seen other posters asking homework to be done for them, so here is basically what we tell them: DO IT YOURSELF.
And we realize that very possibly you could fail your class from that and have to drop out. This may be a good thing because it will help keep the demand for technical workers up, and thus, keep the pay high.
On the other hand, if you choose to actually do the assignment then we will be happy to give comments on your code. Please post it when you have some and until then, best wishes with what ever you choose to do.
BTW: the solution you allude to requires a field also... and in reality, you already gave the answer--just implement it. If you do not know how: well, maybe you should do one of the following:
1-read and study the Java Tutorial
2-pay more attention to class
3-read your textbook for your class
4-go to class
5-stay awake in class
6-pay attention in class
7-talk to your teacher
8-withdraw from the class
9-change your major -
Reading counter in loop .... slow!
I asked this question on the labview board, hoping it gets more response on the counter board.
http://forums.ni.com/ni/board/message?board.id=170&message.id=293236#M293236
Basically I need to read the counter to measure the speed of rotation (quadrature encoders with a max freq of 100 khz) and close the loop with PID as fast as possible, prefereably > 5khz. With one counter I can get around 10 khz, when I go to three counters (which is what I need) I can barely get to 3 khz. Once I'm actually doing other things in the system I can't get acceptable performance. I've got a PXI-8106 RT and PXI-6608, running RT. Seems like Daqmx is pretty inadequate at doing counter readings acceptably fast with what should be a top notch system.
I've attached pictures of what I'm doing with the counters which seems like it should work fine.
Any help would be greatly appreciated.
Thanks
Henri
Attachments:
Setup Counter.JPG 72 KB
Main Loop.JPG 55 KB
Read Counter.JPG 67 KBI *think* you'll get better results with some code work. I assume the unshown TRUE case in your Read code is pretty much empty and just passes through the data read before the case structure?
1. One thing I notice that may matter is that on an error in the Read code, you stop the task and then perform a Read without an explicit Start. I also didn't see an explicit Start in the Setup code, so it appears that you're depending on the "auto-start" behavior that kicks in when you Read from a previously-unstarted task. I'm not 100% sure of this, but I think the DAQmx State model might make that mode of operation less efficient than if you were to explicitly Start the task outside your main loop (and again inside the error case of the Read). I've made that a personal habit, and I think I based it on reading something to that effect in the help or here on the site -- somewhere. In any case, it won't hurt to try. Also, when you *do* restart on an error, I don't think you should need to call the 'Overwrite' property or the DAQmx Timing vi. The task should remember those settings if you merely stop rather than clear it.
2. I'm a bit uncomfortable seeing 0-valued timeouts, and wonder if those may cause occasional timeout errors which cause you to execute the slower error case in the Read code. Not sure though -- maybe it's ok when you also request -1 = 'all available samples'.
3. In the screenshot, the Timed Loop is set for 5 kHz. I assume you varied the requested rate to try to make the loop run faster?
4. Dunno what's inside the 'Loop % Used' subvi you call, but make sure that isn't bogging you down.
5. When you made calls to 3 counter tasks, were they sequential or parallel? The timing results you reported sounds like their times were additive, kind of implying a sequence. Be sure to try dropping them in parallel. (Of course, there's a chance this might actually become slower as DAQmx negotiates more parallel threads -- you'd have to benchmark it).
6. Dunno much about Shared Variables on RT, but think I recall that you can use them in RTFIFO mode. If so, do it. If they aren't in that mode, they may be responsible for some overhead.
7. This one's more of a style thing than a speed thing. You read 'all available samples' which returns an array of recent values. Then you retain only the first element, which is the oldest value there. I would expect that you'd either want to compute an average on the array, or keep the last array element which is the most recent value.
8. There's another way to extract only the most recent data in your calls to DAQmx Read. In your Setup code you could call the DAQmx Read property node to set RelativeTo = MostRecentSample, and Offset = -n. These settings will persist. Then you could call DAQmx Read to request n samples and it will immediately return the most recent ones.
Hope something here proves useful...
-Kevin P.
P.S. Just followed your link to the other thread. Should have done it before posting -- looks like that thread is the more active one and I'll direct followups there.
Message Edited by Kevin Price on 01-16-2008 05:35 PM -
10.5.2 upgraders read here - reboot "loop"
I just upgraded a Mac Mini (Core 2 1.6) to 10.5.2 here at work today. The machine went from 10.4.11 to 10.5 via an OS upgrade (not an erase and install). After installing the update the machine rebooted itself 5 times (never making it to the desktop). On the last bootup the machine made it back to the desktop. It now appears to be fine.
So, long story short don't panic if your machine reboots itself a few times. It (may) be ok!
Message was edited by: schleppythis happened to me also. 4 reboots rather than 5 but still... Maybe because I used the combo update?
Message was edited by: V.K. -
While loop never stops after reading the result
I 'amattaching the program with thismessage in which while loop never stops, going on continuing until I stops it manualy using the off button What i have to do to get it off automatically afetr execution and reading the query and getting the result in Read in Front panel
Attachments:
PMd VI.vi 33 KBYour stop condition is "continue if true". This means that, unless you press the button, the while loop will stop after one iteration.
First, you should change the termination condition to "stop if true".
Then you should make the stop button "latch when released" (right-click..mechanical action). Else you don't have a well defined state after the program stops.
You should decide on a reasonable loop rate and enter it for the wait control. (beter use a diagram constant if the value is always the same).
Why do you need to continue reading in a loop? Are you expecting the response to change over time?
Do you want to keep appending to the string indicator or only show the latest characters received?
Maybe you also need a wait between the writing and reading?
Delete the ms timer value indicator, it is completely useless.
Do you get any error codes?
Don't use the run continous button. Use the plain run button.
What device are you communicating with? Do you have documentation?
LabVIEW Champion . Do more with less code and in less time . -
I need to loop through 1 table and read another until a value changes
i need to read a table and sum the quantity field until a reason code changes. how do I go about doing this?
sort itab by reasoncode.
Loop at itab.
quantiy = quanity + itab-quantity.
at end of reasoncode.
jtab-reasoncode = itab-reasoncodee.
jtab-sum = quantity.
append jtab.
clear quantity.
endat
endloop.
or
sort itab by reasoncode.
loop at itab.
at end of reasoncode.
sum.
jtab = itab.
append jtab.
endat.
endloop.
or
let us say itab and jtab are two tables and you want to loop through itab and read jtab for reasoncodes.
if jtab has only one entry for each entry in itab then use read else use loop.
loop at itab.
loop at jtab where reasoncode = itab-reasoncode.
quantiy = quantiy + jtab-quanity.
endloop.
endloop.
or
loop at itab.
read table jtab with key reasoncode = itab-reasoncode.
if sy-subrc eq 0.
endif
endloop. -
is there anything wrong with this code
clear wa_bseg.
loop at t_final into wa_final.
loop at t_bseg1 into wa_bseg where belnr = wa_final-belnr
and gjahr = wa_final-gjahr.
*and zfbdt = wa_final-zfbdt.
if sy-subrc eq 0 .
wa_final1 = wa_final.
append wa_final1 to t_final1.
clear wa_final1.
endif.
clear wa_bseg.
endloop.
*clear wa_final.
endloop.Hi,
Instead of using loop within loop , use read statement within loop it will improve program performance.
try this below logic..
clear wa_bseg.
loop at t_final into wa_final.
read table t_bseg1 into wa_bseg with key belnr = wa_final-belnr
gjahr = wa_final-gjahr.
if sy-subrc eq 0 .
wa_final1 = wa_final.
append wa_final1 to t_final1.
endif.
clear: wa_bseg, wa_final1,wa_final.
endloop.
Regards,
N M Poojari.
Edited by: Nilambari Poojari on May 27, 2008 9:06 AM -
I can't figure out how to stop a while loop in my labview program.
When the user presses the Run arrow in the toolbar I want my program to begin reading the serial port for GPS messages. These messages should be displayed on the front panel. Currently I have this read/display in a while loop. The program is also waiting for an extrenal trigger. When that trigger arrives, I want to grab the current string from the serial port and save it and continue reading and displaying the serial/gps string. This trigger starts the other parts of the program- signal generation, recording, and saving data which need to run concurrently with the serial/gps reading/displaying. Once the AO and AI have finished and the data have been written to disk, I want the program to stop. The serial/gps messages should be updating this whole time. Only when the data are written to disk should the whole program end. This whole sequence of events should only be done once when the user preses the Run arrow.
So far I'm unable to pluck the serial string when the trigger comes in if I'm watching the serial port all the time. The program also doesn't stop when it finishes writing to disk because the read serial while loop is still running. I don't want to use a front panel stop button. The program should stop itself when the data havebeen written.
I'm really stumped on this one but I'm new to LabVIEW so I'm sure there's an easy solution to this.
Thanks for any and all help.
Attachments:
SPoleLakeChirp.vi 199 KBDennis and altenbach- Thank you both for your patience.
I was trying to do just what Dennis suggested-"As I said, setting a local variable is one way." even before posting to this forum, but I couldn't get my local variables to reflect changes made elsewhere in the program and I wasn't able to wire from them because they were writes. The critical part I was missing was how to change a local variable from a write to a read. It was staring me in the face the whole time- just right click. When I finally found it, my problems were solved.
altenbach- thank's for putting the figures together. I do understand the logic and wiring there, but I was really trying to avoid stop buttons. The program should be smart enough to figure out when to stop. And using local variables turns out to be one way of solving this. I still have some clean up to do, but I've included my current working version just so you can see how I implimented your suggestions. There's still a lot of clean up to be done, but I'm delighted to be able to watch the serial/gps messages until I'm done reading in data. At first I had this stop variable set in the final sequence frame. That didn't work because I wasn't getting to the final frame because the loop wasn't finishing. Once I placed the stop variable in the same frame as the while loop it began stopping when it should.
If you have other comments/critiques about the wiring diagram I'm earger to hear them. I'm considering the structure finished, however. It still needs cleaning up and commenting, but I'm satisfied with the functionality.
Thanks,
Peter
Attachments:
SPoleLakeChirp.vi 210 KB -
How to Read data from a table which is defined as a field in another table
Hi
Iam working with FM: 'CUCB_GET_CONFIGURATION'
<b> Import parameter configuration as a table.</b>
<u>but configuration has another table as a field.</u>
i want to read the inner table fields.
how can i read the table which is defined as field in configuration table.
Please try to give me a solution.
can i have the declartions too....
Thanks,
sriHi jonnakuti,
1. simple
2.
DATA : CONFG TYPE IBCO2_INSTANCE_TAB2.
<b>DATA : WA TYPE LINE OF IBCO2_INSTANCE_TAB2.</b>
3. just copy paste
4.
report abc.
TYPE-POOLS : IBCO2.
DATA : INSTANCE TYPE CUIB_CUOBJ.
DATA : CONFG TYPE IBCO2_INSTANCE_TAB2.
DATA : WA TYPE LINE OF IBCO2_INSTANCE_TAB2.
CALL FUNCTION 'CUCB_GET_CONFIGURATION'
EXPORTING
INSTANCE = INSTANCE
IS_BUSINESS_OBJECT =
IV_MOMENT =
IV_WITH_DB_INSTANCE =
IMPORTING
IBASE =
CONFIGURATION = CONFG
EO_CBASE_REF =
EXCEPTIONS
INVALID_INPUT = 1
INVALID_INSTANCE = 2
INSTANCE_IS_A_CLASSIFICATION = 3
OTHERS = 4
read like this
LOOP AT CONFG INTO WA.
ENDLOOP.
regards,
amit m. -
Read multiple files and save all into one output file(AGAIN)
Hi, guys
I need your help for reading data from multiple files and save the results into one output file. When files are selected from file chooser, my program read the data line by line , do some calculations and save the result into the output. I made an array to store input files and it seems to be working fine, but when it comes to SaveFile() function, issues NullPointException message.
public class FileReduction1 extends JFrame implements ActionListener
// GUI definition and layout
/* ACTION PERFORMED */
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Open File")) getFileName();
/* OPEN THE FILE */
private void getFileName() {
// Display file dialog so user can select file to open
JFileChooser fileChooser = new JFileChooser();
fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
fileChooser.setMultiSelectionEnabled(true);
int result = fileChooser.showOpenDialog(this);
// If cancel button selected return
if (result == JFileChooser.CANCEL_OPTION) return;
if (result == JFileChooser.APPROVE_OPTION)
files = fileChooser.getSelectedFiles();
textArea.setText("");
if(files.length>0)
filelist="";
System.out.println("files length"+files.length);
for(int i=0;i<files.length;i++)
System.out.println(files.getName());
filelist+=files[i].getName()+" ,";
if (checkFileName(files[i]) )
openButton.setEnabled(true);
readButton.setEnabled(true);
textArea.append("file "+files[i].getName()+"is a proper file"+"\n");
readFile(files[i]);
textfield.setText(filelist);
else{JOptionPane.showMessageDialog(this,"Please select file(s)",
"Error 5: ",JOptionPane.ERROR_MESSAGE); }
// Obtain selected file
/* READ FILE */
private void readFile(File fileName_in) {
// Disable read button
readButton.setEnabled(false);
// Dimension data structure
getNumberOfLines(fileName_in);
data = new String[numLines][4];
// Read file
readTheFile(fileName_in);
// Rnable open button
openButton.setEnabled(true);
/* GET NUMBER OF LINES */
/* Get number of lines in file and prepare data structure. */
private void getNumberOfLines(File fileName_in) {
int counter = 0;
// Open the file
openFile(fileName_in);
// Loop through file incrementing counter
try {
String line = fileInput.readLine();
while (line != null) {
counter++;
System.out.println("(" + counter + ") " + line);
line = fileInput.readLine();
numLines = counter;
closeFile(fileName_in);
catch(IOException ioException) {
JOptionPane.showMessageDialog(this,"Error reading File",
"Error 5: ",JOptionPane.ERROR_MESSAGE);
closeFile(fileName_in);
System.exit(1);
/* READ FILE */
private void readTheFile(File fileName_in)
// Open the file
//int row=0;
int col=0;
openFile(fileName_in);
System.out.println("Read the file");
// Loop through file incrementing counter
try
String line = fileInput.readLine();
while (line != null)
boolean containsDoubles = false;
double temp;
String[] lineParts = line.split("\t");
try
for (col=0;col<lineParts.length;col++)
temp=Double.parseDouble(lineParts[col]);
data[row][col] = lineParts[col];
containsDoubles = true;
System.out.print("data["+row+"]["+col+"]="+lineParts[col]+" ");
} catch (Exception e) {row=0; col=0; temp=0.0;}
if (containsDoubles){ row++;}
System.out.println();
line = fileInput.readLine();
catch(IOException ioException)
JOptionPane.showMessageDialog(this,"Error reading File", "Error 5: ",JOptionPane.ERROR_MESSAGE);
closeFile(fileName_in);
System.exit(1);
//System.out.println("length"+data.length);
closeFile(fileName_in);
process(fileName_in);
/* CHECK FILE NAME */
/* Return flase if selected file is a directory, access is denied or is
not a file name. */
private boolean checkFileName(File fileName_in) {
if (fileName_in.exists()) {
if (fileName_in.canRead()) {
if (fileName_in.isFile()) return(true);
else JOptionPane.showMessageDialog(null,
"ERROR 3: File is a directory");
else JOptionPane.showMessageDialog(null,
"ERROR 2: Access denied");
else JOptionPane.showMessageDialog(null,
"ERROR 1: No such file!");
// Return
return(false);
/* OPEN FILE */
private void openFile(File fileName_in) {
try {
// Open file
FileReader file = new FileReader(fileName_in);
fileInput = new BufferedReader(file);
catch(IOException ioException) {
JOptionPane.showMessageDialog(this,"Error Opening File",
"Error 4: ",JOptionPane.ERROR_MESSAGE);
textArea.append("OPEN FILE\n---------\n");
textArea.append(fileName_in.getPath());
textArea.append("\n");
//System.out.println("File opened successfully");
/* CLOSE FILE */
private void closeFile(File fileName_in) {
if (fileInput != null) {
try {
fileInput.close();
catch (IOException ioException) {
JOptionPane.showMessageDialog(this,"Error Opening File",
"Error 4: ",JOptionPane.ERROR_MESSAGE);
System.out.println("File closed");
private void process(File fileName_in) {
//getNumberOfLines();
//data = new String[numLines][3];
// Read file
double temp,temp1;
//readTheFile();
//System.out.println("row:"+row);
//int number=data.length;
//System.out.println(number);
for (int i=0; i<row; i++)
temp=Double.parseDouble(data[i][1]);
sumx+=temp;
temp1=Double.parseDouble(data[i][3]);
sumy+=temp1;
multixy+=(temp*temp1);
square_x_sum+=(temp*temp);
square_y_sum+=(temp1*temp1);
//System.out.println("Sum(x)="+sumx);
double tempup=(row*multixy)-(sumx*sumy);
double tempdown=(row*square_x_sum)-(sumx*sumx);
slope=tempup/tempdown;
double tempbup=sumy-(slope*sumx);
intb=tempbup/row;
double tempside=(row*square_y_sum)-(sumy*sumy);
double cordown=Math.sqrt(tempdown*tempside);
corr=tempup/cordown;
r_sqrt=corr*corr;
textArea.append("Data for file"+ fileName_in.getName()+" have been processed successfully.");
textArea.append("\n");
textArea.append("Please enter output file name including extension.");
System.out.println("number"+row);
System.out.println("slope(m)="+slope);
System.out.println("intecept b="+intb);
System.out.println("correlation="+corr);
System.out.println("correlation="+r_sqrt);
saveFile();
private void saveFile()
textArea.append("SAVE FILE\n---------\n");
if (openFile1())
try {
outputToFile();
catch (IOException ioException) {
JOptionPane.showMessageDialog(this,"Error Writing to File",
"Error",JOptionPane.ERROR_MESSAGE);
private boolean openFile1 ()
// search for the file path
StringBuffer stringpath;
title=textfield1.getText().trim();
int temp=fileName_in.getName().length();
int temp_path=fileName_in.getPath().length();
int startd=(temp_path-temp);
stringpath=new StringBuffer(fileName_in.getPath());
stringpath.delete(startd, temp_path+1);
//System.out.println("file-path="+temp_path);
//System.out.println("length-file="+temp);
path=stringpath.toString();
fileName_out = new File(path, title);
//System.out.println(file_out.getName());
if (fileName_out==null || fileName_out.getName().equals(""))
JOptionPane.showMessageDialog(this,"Invalid File name",
"Invalid File name",JOptionPane.ERROR_MESSAGE);
return(false);
else
try
boolean created = fileName_out.createNewFile();
if(created)
fileOutput = new PrintWriter(new FileWriter(fileName_out));
fileOutput.println("File Name"+"\t"+"Slope(m)"+"\t"+"y-intercept(b)"+"\t"+"Coefficient(r)"+"\t"+"Correlation(R-Squared)");
return(true);
else
fileOutput = new PrintWriter(new FileWriter(fileName_out,true));
return(true);
catch (IOException exc)
JOptionPane.showMessageDialog(this,"Please enter the file name","Error",JOptionPane.ERROR_MESSAGE);
return(false);
private void outputToFile() throws IOException
// Initial output
textArea.append("File name = " + fileName_out + "\n");
// Test if data exists
if (data != null)
fileOutput.println(fileName_in.getName() +"\t"+ slope+"\t"+intb+"\t"+corr+"\t"+r_sqrt);
textArea.append("File output complete\n\n");
else
textArea.append("No data\n\n");
// End by closing file
initialcomp();
fileOutput.close();
private void initialcomp()
slope=0.0;
intb=0.0;
corr=0.0;
r_sqrt=0.0;
sumx=0.0; sumy=0.0; multixy=0.0; square_x_sum=0.0; square_y_sum=0.0;
for(int i=0;i<data.length;i++)
for(int j=0;j<data[i].length;j++)
data[i][j]=null;
/* MAIN METHOD */
public static void main(String[] args) throws IOException
// Create instance of class FileChooser
FileReduction1 newFile = new FileReduction1("File Reduction Program");
// Make window vissible
newFile.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
newFile.setSize(500,400);
newFile.setVisible(true);
Sorry about the long lines.
As you can see, all input files saved in array called files, however when OpenFile1() function is called, it take input (fileName_in) as a single file not an array. I'm assuming this causes the exception.
When there's muptiple inputs, program should take each file from getFileName() to outputToFile() sequentially.
Does anybody have an idea to solve this?
Thanks a lot!!you naming convention is confussing. you should follows Java naming convention..you have a getXXX but decalred the return type as "void"...get usully means to return something...
your code is doing too much..and hard to follows..
1. get the selected files
for each selected file
process the file and return the result
write out the result.
/** close the precious resource */
public void closeResource(Reader in){
if (in != null){
try{ in.close(); }
catch (Exception e){}
/** get the total number of line in a file */
public int getLineCount(File file) throws IOException{
BufferedReader in = null;
int lineCount = 0;
try{
in = new BufferedReader(new FileReader(file));
while ((in.readLine() != null)
lineCount++;
return lineCount;
finally{ closeResource (in); }
/** read the file */
public void processFile(File inFile, File outFile) throws IOException{
BufferedReader in = null;
StringBuffer result = new StringBuffer();
try{
in = new BufferedReader(new FileReader(inFile));
String line = null;
while ((in.readLine() != null){
.. do something with the line
result.append(....);
writeToFile(outFile, result.toString());
finally{ closeResource (in); }
public void writeToFile(File outFile, String result) throws IOException{
PrintWriter out = null;
try{
out = new PrintWriter(new FileWriter(outFile, true)); // true for appending to the end of the file
out.println(result);
finally{ if (out != null){ try{ out.close(); } catch (Exception e){} } }
}
Maybe you are looking for
-
Firewire 400 to 800 cable not working
Hi I have just bought a third party Firewire 400 to 800 cable to connect from my Lacie drive's 800 port to the 400 port on my iBook. When I do this, the drive does not mount at all. Does anyone know why? best Aldo
-
Error during deployment ear file on IAS
Hello, when deploying an ear file in a container (using the EM) i'm getting following error after i select the ear file and enter my application name : Invalid J2EE application file specified - Nested exception Root Cause: Invalid Document Key OC4J_I
-
I am unable to play Pandora through my USB connection (via Lightening cable) in my 2011 Honda Accord with my iPhone 5. Any idea if a fix will be available?
-
Hello question about blown out layout and designer
hello im a web designer....my format is to slice my layout in fireworks....then I bring things into dreamweaver and then place flash files into placed blank spots...........my problem is I notice things get out of line and blown out.....how can i fix
-
Internet Explorer 9 stops using PAC File
Hi, several machines that have Internet Explorer 9 installed suddenly stopped connecting to the internet using a PAC file. Chrome as well as Firefox work with the PAC file set in IE, setting a static proxy adress in the Proxyserver field in IE works