Wait until text-file is REALLY close
How can I protect file-write if power is shutdown imediately?
I write tmp file and I need read data from this file after power shutdown(or hard reset), but file is sometimes corrupted.
FileWriter ff = new FileWriter(lastFILE,false); //new file
f.write("<kredit><" + kredit + ">");
f.write("<pot><" + pot + ">");
f.write("<bonus><" + bonus + ">");
f.close();Error is sometimes occuring when I make test:
1)I write data to file
2) wait aprox. 1 sec (in Java there is 1 second after close function)
3) turn off PC, switch-off (or hard reset)
4) turn on PC and file is corrupted
I use Windows XP(ntfs) on Compat Flash Card. I turned off write caching in Windows for HDD but problem is still during.
I think error is in Operation System because there is write caching on HDD and that's why I am looking for some function which will be wait if file is really close.
Any Ideas?
Thanks.
crosspost
http://forum.java.sun.com/thread.jspa?messageID=9828180
Similar Messages
-
How can i get program to wait until file is loaded?
Hi all,
I keep getting a null pointer exception error thrown when it shouldn't. I'm 99% certain that its being generated because the program speed is faster than the load file time. Is there any way to make the program wait until the file is finished loading? I know you can set up a for loop that will take up some time but I wanted it to be more accurate so that no errors will occur on any machine. Here is the code
RunMainProg();
String[] TempHolder = new String[HowMany*2];
try
BufferedReader readerOne = new BufferedReader(new FileReader("TempMDLFile.txt")); // file just save from RunMainProg()
String lineOne;
int i=0;
while ((lineOne = readerOne.readLine()) != null)
if(i>=TempHolder.length)
break;
TempHolder=lineOne;
i++;
readerOne.close();
catch (IOException f)
MakeDialog ErrorDialog = new MakeDialog(TopWindow, "Load Error", "Error - The file you entered does not exist", "Error", "OK", "OK", 0, 0);
for(int i=0; i<TempHolder.length; i++)
if(TempHolder[i] == null)
i=0;
FormatData TestSequences = new FormatData(TempHolder); // problem occurs at this line
I have looked all over and can't seem to find a way to verify if the file is loaded, or to get it to wait until it has. Any help would be much appreciated. Especially if you can supply some code snippets :)
Much obliged
Drb2k2okay, I added some test code that I was using to try and iron out the problem. Perhaps its best if I run through what happens.
1. I get the data from the text box, and an external program is run which generates some text files. These files are then loaded and examined and some new data is appended to the old. This is the process
FormatData TestSequences = new FormatData(TempHolder); Now every time its run first time around its fine.
2. When I try and do exactly the same thing with the new appended set of data the null exception is thrown. Now Dr Clap, I thought exactly the same as you did, but... If i add the following bit of code before the FormatData call..
for(int i=0; i<TempHolder.length; i++)
System.out.println(TempHolder);
It will produce the data without the appended info, and some null sequences.
The size of TempHolder is adjusted depending on the amount of data submitted, so somewhere along the line its just not working.
3. Now for the fun part, eventually if you put the call in a loop it will correct itself and produce the outcome, but needless to say i'd rather not have my program catching a load of nullpointerException errors.
Finally as for the code
for(int i=0; i<TempHolder.length; i++) { if(TempHolder[i] == null) i=0; }That was an attempt to stall the program until no null sequences were found. Sort of getting around the problem in 3.
Dr Clap is a legend on these posts and his advice is well recieved but I have no idea how to view a stack trace or what benefit it has. Any tips on this would be great.
Thanks for your help so far
drb2k2 -
Hello, sorry for my english and thanks for all.
I know how can to use an URLconnection for to get the file size for download and after to get the InputStream read it and to get the progress download.
If in the URLconnection I setUseCaches(true), I must to wait until the file is all download an after I can read the InputStream.
If in the URLconnection I setUseCaches(false), I can read the InputStream at the same time that the file is downloading.
I have two questions:
- if I setUseCaches(true), why I must to wait until the file is all download an after I can read the InputStream?
- how can I get the progress download if setUseCaches(true) in the URLconnection?
very thanksThis is the code that I've used:
try{
URLConnection urlconnection;
urlconnection = (new URL(getDocumentBase(), "beni0271.jpg")).openConnection()
urlconnection.setUseCaches(true);
//If in the URLconnection I setUseCaches(true), I must to wait until the file is all download an after I can read the InputStream.
//If in the URLconnection I setUseCaches(false), I can read the InputStream at the same time that the file is downloading.
System.out.println(urlconnection);
length = urlconnection.getContentLength();
inps = urlconnection.getInputStream();
System.out.println(inps);
}catch(MalformedURLException e){
System.out.println(e);
}catch(IOException e){
System.out.println(e);
} -
Loading a text file into a global variable issue - really a global var?
From all the documentation and examples I can find, it appears that it would be
correct to create a global array variable [outside of any functions] to load image names into,
then use these images for a slideshow. I want to make the app dynamic, in that changing the text file gives a new set of images.
The global variable goes null [no values] after the load event listener. Why is that?
Isn't global, well global, and alive for the duration of the SWF?
PARAMS.TXT:
monthNames=January,February,March,April,May,June,July,August,September,October,November,De cember&dayNames=Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
CODE:
var dNames:Array = new Array();
var mNames:Array = new Array();
var request:URLRequest = new URLRequest("images/params.txt");
var variables:URLLoader = new URLLoader();
variables.dataFormat = URLLoaderDataFormat.VARIABLES;
variables.addEventListener(Event.COMPLETE, completeHandler);
try
variables.load(request);
catch (error:Error)
trace("Unable to load URL: " + error);
trace("2 mNames 2: " + mNames[2]);
trace("2 dNames 3: " + dNames[3]);
stop();
function completeHandler(event:Event):void
var loader:URLLoader = URLLoader(event.target);
dNames = loader.data.dayNames.split(",");
mNames = loader.data.monthNames.split(",");
trace(loader.data.dayNames);
trace("1 mNames 2: " + mNames[2]);
trace("1 dNames 3: " + dNames[3]);
OUTPUT:
2 mNames 2: undefined
2 dNames 3: undefined
Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
1 mNames 2: March
1 dNames 3: Wednesday
How do I access these values after loading from the external file, after the load?
Thanks in advance.The statement you quoted from whatever Adobe documentation is correct.
If you want to load the data into the arrays before anything else happens, then have anything else that happens execute via the completeHandler function... after the data is loaded and processed into the arrays.
the command: loadFile() executes before the trace("2:" +images[4]); command. The loadFile function is processed and the loading process BEGINS... but starting the loading does not delay the main processing from continuing down the line--the loading itself becomes a secondary/background task. The command was to execute the loadFile function and the processing of that function was completed. If you don't believe so, then add a trace...
function loadFile():void
vars.dataFormat = URLLoaderDataFormat.VARIABLES;
vars.addEventListener(Event.COMPLETE, onComplete, false, 0, true);
vars.load(new URLRequest("images/fnames.txt"));
trace("started loading");
If you add that trace, you should see that the loadFile function execution is completed and the next line in your code is then processed... trace(2....)
The addEventlistener does not stop anything. The addEventListener code is assigning a monitor, not a traffic controller... it is telling the monitor to indicate when the data has finished loading. It is not telling anything to stop program execution.
So if you want to wait until the data is loaded before you do anything else... it goes....
function onComplete(evt:Event):void
var urlVars:URLVariables = evt.target.data;
images = vars.data.images.split(",");
tnails = vars.data.thumbnails.split(",");
................HERE................. -
File Adapter -- Picking has to wait untill it get fully loaded/write.
Hi All,
I need to pick the files from a folder and I need to pick the files only which has been written completely.
I should not pick the file in the middle while writing, I need to wait untill it finishes the writing completely.
Is there any setting I can put in Sender File adapter to do this?
Thanks
SeemaNithya,
>> Try to increase the processing time in the sender communication channel, so that it allows you to completely load the file. Check the time which is needed to upload the file to the directory manually and correspondingly change the processing time.
We do not know exactly at what time the file will be placed in the folder. It may be at any time. So I cannot put the processing time accurately.
Aamir,
>> If you are picking from FTP,MSecs wont work there.the sender program which writes the file must write the file in some temporary format like .dat etc and once the file is complete it should change the filename to .txt,configure the sender file adapter to pick only *.txt files.
This is a good idea. But I don't think I can ask them to change at the other end as it is working previously with other middleware.
Guys,
Can you please advice which is the best thing we can do at this point of time.?
Thanks
Seema. -
Really want to buy an IQ800 - but wait until Windows 7?
Hi,
I REALLY want to buy a TouchSmart IQ800, but I was told to wait until Windows 7 comes out - that won't be for another 8 months!
I was also told that by that time, they probably will offer bigger CPU's, Memory, and Video Cards...
Any input would be greatly appreciated!
Thanks!I've got the IQ810 TS, which is the United Kingdom version i presume, and have played with it so much despited being a novist with PC's, i can tell thats its a beauty to have one of these babies, and to retirate i'll call her my baby, its like a new toy or mobile phone you configure to a very satisfactory taste. I manager to creat a dual boot OS containing the Original Os that came from the manufacture, mirroring each other, reason is siimply to upgrade one of the OS to Window 7 whlie retainning the original sorfwares and drivers, my joy isn't just having the TS and what it potentially could do but the journey it took me to getting to where i am.
My advise would be, depending how urgently you like to have one, weigh the positive against the negative, having in mind when it come to computers, elctronics or TECHNOLOGY, its ALWAYS CHANGING, and as for window 7 RC if you decide to upgrade to, Window 7 will expire next year, by then MS would have released the window 7 for consumers to everyone.
Even with the wall mount i got as additional kit, i've left mine on a coffee table, better experience, accessiblity and conviences, to be honest i ffind it difficult to use anything smaller than a 25" screen or Window 7 with the multi touch, split screen for comparison, multimedia i.e t.v, 2D & 3D designs programs.
I think i've said enough, have fun like i did mate.......
Message Edited by Muteman on 05-23-2009 01:50 PM -
there was an error importing some photos from my iphone, and since then I can not close the program ... it gives the mesage 'please wait until import is conclued'...but nothing is being tranfered. Any help ? Iphoto version 9.5.1
Force Quit the application from the Apple menu.
-
when i try to close my iPhoto app on my air it continuously says wait until import is finished and it won't let me exit the app and i cant even turn off my laptop, what can i do to close it?
Welcome to Apple Support Communities
Press Alt, Command and Esc keys or go to > Force Quit, choose iPhoto and force close it. -
Well I'm about to send a imessage to a friend who might not be in wifi or cellular network so what will Happen
You mean to say when I enable send as sms when imessage is unavailable the imessage will be send the message as sms when my friend is not connected to Internet and when I disable it then it will wait until friend is back to wifi or cellular
-
Reading in a text file to GUI for later analysis
Good Morning any and everyone,
I'm trying to get a piece of code working to read in a text file and it isn't working very well. The code has been seriously crunched together from a multitude of sources so I suspect that the error has occurred from there.
The errors that are occurring are "Can't Find Symbol" errors. Only 2 of them though which is a lot less than I had earlier. Now I'm just banging my head against the wall.
Has anyone got any suggestions as to where I'm going wrong? Anything greatly appreciated.
(PS> Please be gentle, I'm still a newbie)
Thanks.
import java.util.*; // required for List and ArrayList
import java.io.*; // required for handling and IOExceptions
import javax.swing.*;
public class textAnalyser extends JFrame // implements ActionListener
// the attributes
// declare a TextArea
private JTextArea viewArea = new JTextArea(10,55);
// declare the menu components
private JMenuBar bar = new JMenuBar();
private JMenu fileMenu = new JMenu("File");
private JMenu quitMenu = new JMenu("Quit");
private JMenuItem selectChoice = new JMenuItem("Select");
private JMenuItem runChoice = new JMenuItem("Run");
private JMenuItem reallyQuitChoice = new JMenuItem("Really quit");
private JMenuItem cancelChoice = new JMenuItem("Cancel");
// declare an attribute to hold the chosen file
private File chosenFile;
// the constructor
public textAnalyser()
setTitle("Text Analyser"); // set title of the frame
add(viewArea); // add the text area
// add the menus to the menu bar
bar.add(fileMenu);
bar.add(quitMenu);
// add the menu items to the menus
fileMenu.add(selectChoice);
fileMenu.add(runChoice);
quitMenu.add(reallyQuitChoice);
quitMenu.add(cancelChoice);
// add the menu bar to the frame
setJMenuBar(bar);
// add the ActionListeners
// selectChoice.addActionListener(this);
// runChoice.addActionListener(this);
// reallyQuitChoice.addActionListener(this);
// cancelChoice.addActionListener(this);
// configure the frame
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
setSize(450,200);
setVisible(true);
public void actionPerformed(ActionEvent e)
if(e.getSource() == displayContentsChoice)
try
final int MAX = 300;
FileReader textFile = new FileReader("textfile.txt");
BufferedReader textStream = new BufferedReader(textFile);
int ch; // holds integer value of character
char c; // holds character when type cast from integer
int counter = 0; //counts number of characters read
ch = textStream.read(); //reads the first character from the file
c = (char) ch; //type cast from integer to character
viewArea.append("\n");
/* continue through the file until either the end of the file or the maximum
number of characters allowed have been read*/
while(ch != -1 && counter <= MAX)
counter++; // increment the counter
viewArea.append("" + c); // display the character
ch = textStream.read(); // read the next character
c = (char) ch;
textStream.close();
viewArea.append("\n");
catch(IOException ioe)
if(chosenFile == null) // no file selected
viewArea.append("No file selected\n");
else
viewArea.append("There was a problem reading the file\n");
}A couple of points:
*You've commented out stuff that is needed, like the adding of actionlisteners, the implements actionlistener,...
*Your actionlistener is looking for a menu choice which doesn't exist "displayContentsChoice". Does this menu item need to be created?
*How much of this code have you yourself created? Do you understand its inner working?
*What is the purpose of this code? Is it for work? School? Homework?
Good luck!
/Pete -
VBScript for parsing multiple text files
Hi,
I have around 175 text files that contain inventory information that I am trying to parse into an Excel file. We are upgrading our Office platform from 2003 to 2010 and my boss wants to know which machines will have trouble supporting it. I found a script
that will parse a single text file based upon ":" as the delimiter and I'm having trouble figuring out how to change it to open an entire folder of text files and write all of the data to a single Excel spreadsheet. Here is an example of the text
file I'll be parsing. I'm interested in the "Memory and Processor Information" and "Disk Drive Information" sections mainly.
ABEHRENS-XP Computer Inventory
OS Information
OS Details
Caption: Microsoft Windows XP Professional
Description:
InstallDate: 20070404123855.000000-240
Name: Microsoft Windows XP Professional|C:\WINDOWS|\Device\Harddisk0\Partition1
Organization: Your Mom
OSProductSuite:
RegisteredUser: Bob
SerialNumber: 55274-640-3763826-23029
ServicePackMajorVersion: 3
ServicePackMinorVersion: 0
Version: 5.1.2600
WindowsDirectory: C:\WINDOWS
Memory and Processor Information
504MB Total memory HOW CAN I PULL THIS WITHOUT ":" ALSO
Computer Model: HP d330 uT(DG291A)
Processor: Intel(R) Pentium(R) 4 CPU 2.66GHz
Disk Drive Information
27712MB Free Disk Space ANY WAY TO PULL THIS WITHOUT ":"
38162MB Total Disk Space
Installed Software
Here is the start of the script I have so far. . .
Const ForReading = 1
Set objDict = CreateObject("Scripting.Dictionary")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile("C:\Test\test.txt" ,ForReading)
WANT THIS TO BE C:\Test
Do Until objTextFile.AtEndOfStream
strLine = objTextFile.ReadLine
If Instr(strLine,":") Then
arrSplit = Split(strLine,":") IS ":" THE BEST DELIMITER TO USE?
strField = arrSplit(0)
strValue = arrSplit(1)
If Not objDict.Exists(strField) Then
objDict.Add strField,strValue
Else
objDict.Item(strField) = objDict.Item(strField) & "||" & strValue
End If
End If
Loop
objTextFile.Close
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.Workbooks.Add
intColumn = 1
For Each strItem In objDict.Keys
objExcel.Cells(1,intColumn) = strItem
intColumn = intColumn + 1
Next
intColumn = 1
For Each strItem In objDict.Items
arrValues = Split(strItem,"||")
intRow = 1
For Each strValue In arrValues
intRow = intRow + 1
objExcel.Cells(intRow,intColumn) = strValue
Next
intColumn = intColumn + 1
Next
Thank you for any help.You are The Bomb.com! I had to play around with it to pull some additional data (model and processor) and then write a quick macro to remove the unwanted text and finally I wanted the data to write in columns instead of rows so this is what I ended up with:
Option Explicit
Dim objFSO, objFolder, strFolder, objFile
Dim objReadFile, strLine, objExcel, objSheet
Dim intCol, strExcelPath
Const ForReading = 1
strFolder = "c:\Test"
strExcelPath = "c:\Test\Inventory.xlsx"
Set objExcel = CreateObject("Excel.Application")
objExcel.Workbooks.Add
Set objSheet = objExcel.ActiveWorkbook.Worksheets(1)
intCol = 0
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(strFolder)
For Each objFile In objFolder.Files
intCol = intCol + 1
Set objReadFile = objFSO.OpenTextFile(objFile.Path, ForReading)
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
If (InStr(strLine, "Computer Inventory") > 0) Then
objSheet.Cells(intCol, 1).Value = Left(strLine, InStr(strLine, "Computer Inventory") - 2)
End If
If (InStr(strLine, "Total memory") > 0) Then
objSheet.Cells(intCol, 2).Value = Left(strLine, InStr(strLine, "Total memory") - 2)
End If
If (InStr(strLine, "Computer Model:") > 0) Then
objSheet.Cells(intCol, 3).Value = (strLine)
End If
If (InStr(strLine, "Processor:") > 0) Then
objSheet.Cells(intCol, 4).Value = (strLine)
End If
If (InStr(strLine, "Total Disk Space") > 0) Then
objSheet.Cells(intCol, 5).Value = Left(strLine, InStr(strLine, "Total Disk Space") - 2)
End If
If (InStr(strLine, "Free Disk Space") > 0) Then
objSheet.Cells(intCol, 6).Value = Left(strLine, InStr(strLine, "Free Disk Space") - 2)
End If
Loop
Next
objExcel.ActiveWorkbook.SaveAs strExcelPath
objExcel.ActiveWorkbook.Close
objExcel.Quit
Thanks again!
Hi ,
I am have very basic knowledge about VB scripting, but this code could be the perfect solution i am looking for. could you guide me exactly how to run and test the same , i would be really thankful for your kind and generous support on this.
Thanks ,
Veer -
Cannot seem to read a plain text file
this is actually macromedia flash mx 6.0, which I believe runs AS2 but is compatible with AS3
file = date.txt
file contents: xdate=12/01/2013
the file is in same directory as the .swf
code to read the file contents into a variable:
DateFile = new LoadVars();
DateFile.onLoad = function(ok) {
if (ok) {
var theDate = DateFile.xdate;
DateFile.load("date.txt");
theDate variable is empty
also tried this
file = date.txt
file contents: &xdate=12/01/2013&
DateFile = new LoadVars();
DateFile.load("date.txt");
var theDate = DateFile["xdate"];1. the xdatefile.onload (method?) is automagically invoked by the xdatefile.load method AFTER loading is complete
2.the onload takes care of all the monitoring, byte counting, asynch back office stuff,
for moving file bytes to a variable value, ie, xDatea = xDateFile.xDate; however only after
the finish of that is the actual file data accessible, so the last action within the .onload
is to invoke a function to move the now available data to someplace really useable like
a textbox. This happens in the populateTF function. if I don't get the data moved some
place during the .onload processing I don't have it
not exactly. you don't have to call another function from onLoad. but you must wait until onLoad completes before trying to use the variables defined in onLoad. ie, it is a matter of timing.
so I was able to populate the textbox per the example, However, it seems I still can't
populate a variable and then have that variable content available after the .onload and
populateTF?
I tried this
var xDatec:string (declared earlier)
function populateF(){
txtTestBox2.text = xDatea; //this worked
xDatec = xDateb; //something wrong here. where is xDateb defined?
when I try to use xDatec to populate a texbox, there is no value
txtTestBox3.text = xDatec
// when did you try to use xDatec?
i think you're still failing to see the timing issue. try this test:
file content: &xDate=12012013&
var xDateFile = new LoadVars();
var xDatea:string;
var xDateb:string;
xDateFile.onLoad = function(ok) {
if (ok) {
trace("onLoad finally executes @: "+getTimer());
trace("from this time forward, variables are available");
xDatea = xDateFile.xDate;
trace(xDatea); // should work
xDateb=this.xDate;
trace(this.xDateb); // should work
populateTF();
xDateFile.load("xDate.txt");
trace("loading started @: "+getTimer());
var idx = "xDate";
txtTestBox.text = xDateFile[idx]; // should fail
txtTestBox2.text = xDatea; //should fail
txtTestBox3.text = xDateb; //should fail
txtTestBox4.text = "so I know I got here"; //should work
trace("when trying to use data immediately after loading starts and BEFORE it completes you expect failure. eg @: "+getTimer());
function populateF(){
var idx = "xDate";
txtTestBox.text = xDateFile[idx]; // should work
txtTestBox2.text = xDatea; //should work
txtTestBox3.text = xDateb; //should work
txtTestBox4.text = "so I know I got here"; //should work
trace("when executing code AFTER loading completes you expect success. eg @: "+getTimer()); -
my text is file is getting updated every second, how can i access that updated data from the text file using java. It is just that i am getting some data from an encoder, the encoder is going to put the data into a text file and it is going to update data in some time interval. I just wanna be able access that updated data and display onto the screen until no new data is put in the text file.
Not sure exactly. But something you could try:
use a FileReader object to read characters in until there are no more. Then sleep the thread(probably not the event dispatch thread.., so have a seperate thread that can wait) for some amount of time(like a second) so whatever is writing to the file has time to write... Now if the FileReader isnt detecting that the the file is being written to, then you will need to halt when you are done reading. then close the reader recreate it and skip all the characters that you have read in the previous try. meaning you'll have to keep track of how many chars you've read. -
How to input data into an arraylist from a text file?
I am trying to take data from a text file and put that data into an arraylist. First here is the text file:
[item1, 10, 125.0, item2, 10, 12.0, item3, 20, 158.0]
3
4530.0
[item5, 65, 555.5, item4, 29, 689.0]
2
56088.5
[item7, 84, 34.5, item6, 103, 0.5, item8, 85, 1.36]
3
3065.1The text between the [ ] is the output from my arraylists. I have three arraylists. The first [ ] belongs to arraylist A, the second to arraylist B, and the third to arraylist C. The format of the arraylists is this:
<item name>,<# in stock>,<value of one item>
The first number below the arraylists in the text file represents the number of items in the list. The second number below the arraylists represents the total value of the items in the arraylists.
Here is the class file I have (yes, it does everything):
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Inventory extends Object
public int toAdd = 0;
private boolean done = false; //Are we done yet?
public String strItemName; //The name of the item type.
public int intNumInStock; //The number in stock of that type.
public double dblValueOfOneItem; //The value of one item.
public String strNumberInStock;
public double dblTotalValueA; //The total value of warehouse A.
public double dblTotalValueB; //The total value of warehouse B.
public double dblTotalValueC; //The total value of warehouse C.
public int intWarehouseAItemCount; //Counter for items in warehouse A.
public int intWarehouseBItemCount; //Counter for items in warehouse B.
public int intWarehouseCItemCount; //Counter for items in warehouse C.
ArrayList warehouseAList = new ArrayList(); //Create the Warehouse A ArrayList.
ArrayList warehouseBList = new ArrayList(); //Create the Warehouse B arrayList.
ArrayList warehouseCList = new ArrayList(); //Create the Warehouse C arrayList.
/** Construct a new Inventory object. */
public Inventory()
super();
/**Add items to the Warehouse A ArrayList.*/
private void createWareHouseA()
System.out.println("!" + toAdd + " item types will be added to warehouse A.");
//Cast
String strNumInStock = Integer.toString(intNumInStock);
String strValueOfOneItem = Double.toString(dblValueOfOneItem);
this.strNumberInStock = strNumInStock;
System.out.println("!Initial size of warehouseAList : " +
warehouseAList.size());
//Add items to the array List
warehouseAList.add(this.strItemName);
warehouseAList.add(this.strNumberInStock);
warehouseAList.add(this.dblValueOfOneItem);
System.out.println("!size of arrayList after additions " + warehouseAList.size());
/**Add items to the Warehouse B ArrayList.*/
private void createWareHouseB()
System.out.println("!" + toAdd + " item types will be added to warehouse B.");
//Cast
String strNumInStock = Integer.toString(intNumInStock);
String strValueOfOneItem = Double.toString(dblValueOfOneItem);
this.strNumberInStock = strNumInStock;
System.out.println("!Initial size of warehouseBList : " +
warehouseBList.size());
//Add items to the array List
warehouseBList.add(this.strItemName);
warehouseBList.add(this.strNumberInStock);
warehouseBList.add(this.dblValueOfOneItem);
System.out.println("!size of arrayList after additions " + warehouseBList.size());
/**Add items to the Warehouse C ArrayList.*/
private void createWareHouseC()
System.out.println("!" + toAdd + " item types will be added to warehouse C.");
//Cast
String strNumInStock = Integer.toString(intNumInStock);
String strValueOfOneItem = Double.toString(dblValueOfOneItem);
this.strNumberInStock = strNumInStock;
System.out.println("!Initial size of warehouseCList : " +
warehouseCList.size());
//Add items to the array List
warehouseCList.add(this.strItemName);
warehouseCList.add(this.strNumberInStock);
warehouseCList.add(this.dblValueOfOneItem);
System.out.println("!size of arrayList after additions " + warehouseCList.size());
/**Interpret the commands entered by the user.*/
public void cmdInterpreter()
this.displayHelp();
Scanner cin = new Scanner(System.in);
while (!this.done)
System.out.print(">");
//"line" equals the next line of input.
String line = cin.nextLine();
this.executeCmd(line);
/**Execute one line entered by the user.
* @param cmdLN; The command entered by the user to execute. */
private void executeCmd(String cmdLN)
Scanner line = new Scanner(cmdLN);
if (line.hasNext())
String cmd = line.next();
//What to do when users enter the various commands below.
if (cmd.equals("help"))
this.displayHelp();
else if (cmd.equals("Q!"))
this.done = true;
else if (cmd.equals("F") && line.hasNext())
this.inputFromFile(line.next());
else if (cmd.equals("K") && line.hasNext())
int numItemsToAdd = Integer.valueOf( line.next() ).intValue();
this.toAdd = numItemsToAdd;
this.inputFromKeyboard(numItemsToAdd);
/**What to do if input comes from a file.
* @param inputFile; The name of the input file to process.*/
private void inputFromFile(String inputFile)
Scanner cin = new Scanner(System.in);
System.out.println("!Using input file " + inputFile + ".");
System.out.print("!Enter the name of the output file: ");
String outputFile = cin.next();
System.out.println("!Using output file " + outputFile + ".");
try
BufferedReader in = new BufferedReader(new FileReader(inputFile));
//Scanner in = new Scanner(new File(inputFile));
//Initialize the String variables.
String line1 = null;
String line2 = null;
String line3 = null;
String line4 = null;
String line5 = null;
String line6 = null;
String line7 = null;
String line8 = null;
String line9 = null;
System.out.println(in.equals(",") + " see?");
//System.out.println((char)(char)in.read() + " experiment");
/**This loop assigns values to the string variables based on the
* values on each line in the input file. */
while(in.readLine() != null)
line1 = in.readLine();
line2 = in.readLine();
line3 = in.readLine();
line4 = in.readLine();
line5 = in.readLine();
line6 = in.readLine();
line7 = in.readLine();
line8 = in.readLine();
line9 = in.readLine();
//Print the contents of each line in the input file.
System.out.println("!value of line 1: " + line1);
System.out.println("!value of line 2: " + line2);
System.out.println("!value of line 3: " + line3);
System.out.println("!value of line 4: " + line4);
System.out.println("!value of line 5: " + line5);
System.out.println("!value of line 6: " + line6);
System.out.println("!value of line 7: " + line7);
System.out.println("!value of line 8: " + line8);
System.out.println("!value of line 9: " + line9);
/**Add items to the warehouses.*/
warehouseAList.add(line1);
warehouseBList.add(line4);
warehouseCList.add(line7);
/**Add the item count and total value for warehouse A.*/
int intLine2 = Integer.valueOf(line2).intValue();
this.intWarehouseAItemCount = intLine2;
double dblLine3 = Double.valueOf(line3).doubleValue();
this.dblTotalValueA = dblLine3;
/**Add the item count and total value for warehouse B.*/
int intLine5 = Integer.valueOf(line5).intValue();
this.intWarehouseBItemCount = intLine5;
double dblLine6 = Double.valueOf(line6).doubleValue();
this.dblTotalValueB = dblLine6;
/**Add the item count and total value for warehouse C.*/
int intLine8 = Integer.valueOf(line8).intValue();
this.intWarehouseCItemCount = intLine8;
double dblLine9 = Double.valueOf(line9).doubleValue();
this.dblTotalValueC = dblLine9;
/**Ask the user how many items to add or delete from inventory.*/
System.out.print("Enter the number to add to inventory for " +
warehouseAList.get(0) + ":");
String toAddOrDel = cin.next();
/**Print the contents of all the warehouses. */
System.out.println(" ");
//Print the contents of warehouse A.
System.out.println("!--------------------------------");
System.out.println("!----------Warehouse A:----------");
System.out.println("!--------------------------------");
//Print the item list for warehouse A.
System.out.println(warehouseAList);
//Print the total amount of items in warehouse A.
System.out.println("Total items: " + this.intWarehouseAItemCount);
//Print the total value of the items in warehouse A.
System.out.println("Total value: " + this.dblTotalValueA);
System.out.println("!--------------------------------");
System.out.println("!----------Warehouse B:----------");
System.out.println("!--------------------------------");
//Print the item list for warehouse B.
System.out.println("!warehouseB: " + warehouseBList);
//Print the total amount of items in warehouse B.
System.out.println("Total items: " + this.intWarehouseBItemCount);
//Print the total value of the items in warehouse B.
System.out.println("Total value: " + this.dblTotalValueB);
System.out.println("!--------------------------------");
System.out.println("!----------Warehouse C:----------");
System.out.println("!--------------------------------");
//Print the item list for warehouse C.
System.out.println("!warehouseC: " + warehouseCList);
//Print the total amount of items in warehouse C.
System.out.println("Total items: " + this.intWarehouseCItemCount);
//Print the total value of the items in warehouse C.
System.out.println("Total value: " + this.dblTotalValueC);
in.close();
catch (FileNotFoundException e)
System.out.println("!Error: Unable to open file for reading.");
catch (EOFException e)
System.out.println("!Error: EOF encountered, file may be corrupted.");
catch (IOException e)
System.out.println("!Error: Cannot read from file.");
/**What to do if input comes from the keyboard.
* @param numItems; The total number of items that will be added to the
* Warehouse(s). */
public void inputFromKeyboard(int numItems)
System.out.println("!You will be adding " + numItems + " items to " +
"inventory from the keyboard. ");
this.toAdd = numItems;
Scanner cin = new Scanner(System.in);
//Prompt user for name of output file.
System.out.print("!Enter the name of the output file: ");
String outputFile = cin.next();
/**This loop asks the user for information about the item(s) and inputs
*them into the appropriate array.*/
int count = 0;
while (numItems > count)
//Item name.
System.out.print("!Item name: ");
String addItemName = cin.next();
//Number in stock.
System.out.print("!Number in stock: ");
String addNumInStock = cin.next();
//Initial warehouse.
System.out.print("!Initial warehouse(A,B,C): ");
String addInitWarehouse = cin.next();
//Value of one item.
System.out.print("!Value of one item: ");
String addValueOfOneItem = cin.next();
//Add or delete from inventory
System.out.print("!Enter amount to add or delete from inventory: ");
String strAddOrDelete = cin.next();
System.out.println("!Amount to add or delete: " + strAddOrDelete);
//Cast
int intAddNumInStock = Integer.valueOf(addNumInStock).intValue();
double doubleAddValueOfOneItem = Double.valueOf(addValueOfOneItem).doubleValue();
int intAddOrDelete = Integer.valueOf(strAddOrDelete).intValue();
/**Add intAddNumInStock with intAddOrDelete to determine the amount
* to add or delete from inventory (If a user wishes to remove items
* from inventory simply add negative values). */
intAddNumInStock = intAddNumInStock + intAddOrDelete;
System.out.println("!Inventory after modifications: " + strAddOrDelete);
this.strItemName = addItemName;
this.intNumInStock = intAddNumInStock;
this.dblValueOfOneItem = doubleAddValueOfOneItem;
//Put items into warehouse A if appropriate.
if (intAddNumInStock < 25)
//Increment the warehouse A item count.
this.intWarehouseAItemCount = this.intWarehouseAItemCount + 1;
//Calculate the total value of warehouse A.
this.dblTotalValueA = this.dblTotalValueA + intAddNumInStock * doubleAddValueOfOneItem;
//Create the warehouse A array list.
this.createWareHouseA();
//Put items into warehouse B if appropriate.
if (intAddNumInStock >= 25)
if (intAddNumInStock < 75)
//Increment the warehouse B item count.
this.intWarehouseBItemCount = this.intWarehouseBItemCount + 1;
//Calculate the total value of warehouse B.
this.dblTotalValueB = this.dblTotalValueB + intAddNumInStock * doubleAddValueOfOneItem;
//Create the warehouse B array list.
this.createWareHouseB();
//Put items into warehouse C if appropriate.
if (intAddNumInStock >= 75)
//Increment the warehouse C item count.
this.intWarehouseCItemCount = this.intWarehouseCItemCount + 1;
//Calculate the total value of warehouse C.
this.dblTotalValueC = this.dblTotalValueC + intAddNumInStock * doubleAddValueOfOneItem;
//Create the warehouse C array list.
this.createWareHouseC();
//display helpful information.
System.out.println("!--------------------------------");
System.out.println("!" + addItemName + " is the item name.");
System.out.println("!" + addNumInStock + " is the number in stock.");
System.out.println("!" + addInitWarehouse + " is the initial warehouse.");
System.out.println("!" + addValueOfOneItem + " is the value of one item.");
System.out.println("!--------------------------------------------------");
//Increment the counters.
count++;
/**Create and write to the output file. */
try
//Use the output file specified by the user.
PrintWriter out = new PrintWriter(outputFile);
/**Write warehouse A details.*/
//Blank the first line.
out.println(" ");
//Write the array list for warehouse A.
out.println(warehouseAList);
//Write the amount of items in warehouse A.
out.println(intWarehouseAItemCount);
//Write the total value for warehouse A.
out.println(dblTotalValueA);
/**Write warehosue B details.*/
//Write the array list for warehouse B.
out.println(warehouseBList);
//Write the amount of items in warehouse B.
out.println(intWarehouseBItemCount);
//Write the total value for warehouse B.
out.println(dblTotalValueB);
/**Write warehouse C details.*/
//Write the array list for warehouse C.
out.println(warehouseCList);
//Write the amount of items in warehouse C.
out.println(intWarehouseCItemCount);
//Write the total value for warehouse C.
out.println(dblTotalValueC);
//Close the output file.
out.close();
catch (FileNotFoundException e)
System.out.println("Error: Unable to open file for reading.");
catch (IOException e)
System.out.println("Error: Cannot read from file.");
/**View the contents and the value of each warehouse.*/
System.out.println("!---------------Inventory Summary------------------");
System.out.println("!--------------------------------------------------");
System.out.println("!--------------------LEGEND:-----------------------");
System.out.println("!<item type>, <amount in stock>,<value of one item>");
System.out.println("!--------------------------------------------------");
System.out.println("!------------------Warehouse A:--------------------");
System.out.println("!--------------------------------------------------");
//Display Items in warehouse A.
System.out.println(warehouseAList);
//Total items in warehouse A.
System.out.println("Total items: " + intWarehouseAItemCount);
//Display total value of warehouse A.
System.out.println("Total value: " + "$" + dblTotalValueA);
System.out.println("!--------------------------------------------------");
System.out.println("!------------------Warehouse B:--------------------");
System.out.println("!--------------------------------------------------");
//Display Items in warehouse B.
System.out.println(warehouseBList);
//Total items in warehouse B.
System.out.println("Total items: " + intWarehouseBItemCount);
//Display total value of warehouse B.
System.out.println("Total value: " + "$" + dblTotalValueB);
System.out.println("!--------------------------------------------------");
System.out.println("!------------------Warehouse C:--------------------");
System.out.println("!--------------------------------------------------");
//Display Items in warehouse C.
System.out.println(warehouseCList);
//Total items in warehouse C.
System.out.println("Total items: " + intWarehouseCItemCount);
//Display total value of warehouse C.
System.out.println("Total value: " + "$" + dblTotalValueC);
/**Display a help message.*/
private void displayHelp()
System.out.println("!--------------------------------");
System.out.println("! General Help:");
System.out.println("!--------------------------------");
System.out.println("! ");
System.out.println("!'help' display this help message.");
System.out.println("!'Q!' quit this program.");
System.out.println("!--------------------------------");
System.out.println("! Input File Specific Commands:");
System.out.println("!--------------------------------");
System.out.println("! ");
System.out.println("!'F' <name> type F followed by the name of the " +
"file to be used for input.");
System.out.println("!---------------------------------------");
System.out.println("! Input From Keyboard Specific Commands:");
System.out.println("!---------------------------------------");
System.out.println("! ");
System.out.println("!'K' <number> type K followed by the number of " +
"items that will be added. ");
System.out.println("! ");
}Program file:
public class InventoryProg
public static void main(String[] args)
//Create a new Inventory object.
Inventory test = new Inventory();
//Execute the command interpreter.
test.cmdInterpreter();
}Right now I am stuck on this and I cannot progress any further until I figure out how to input the data in the text file back into a arraylist.
Thanks in advance.Thanks but I figured it out. Heres a sample of the code i used to solve my problem:
try
//Warehouse A BufferedReader.
BufferedReader inA = new BufferedReader(new FileReader(inputFileWarehouseA));
//Warehouse B BufferedReader.
BufferedReader inB = new BufferedReader(new FileReader(inputFileWarehouseB));
//Warehouse C BufferedReader.
BufferedReader inC = new BufferedReader(new FileReader(inputFileWarehouseC));
//Warehouse details BufferedReader.
BufferedReader inDetails = new BufferedReader(new FileReader(inputFileDetails));
//Will hold values in warehouse arraylists.
String lineA = null;
String lineB = null;
String lineC = null;
//Will hold the details of each warehouse.
String line1 = null;
String line2 = null;
String line3 = null;
String line4 = null;
String line5 = null;
String line6 = null;
//Get the item count and total value for each warehouse.
while(inDetails.readLine() != null)
line1 = inDetails.readLine();
line2 = inDetails.readLine();
line3 = inDetails.readLine();
line4 = inDetails.readLine();
line5 = inDetails.readLine();
line6 = inDetails.readLine();
/**Assign the item count and total value to warehouse A.*/
//Cast.
int intLine1 = Integer.valueOf(line1).intValue();
double dblLine2 = Double.valueOf(line2).doubleValue();
//Assign the values.
this.intWarehouseAItemCount = intLine1;
this.dblTotalValueA = dblLine2;
/**Assign the item count and total value to warehouse B.*/
//Cast.
int intLine3 = Integer.valueOf(line3).intValue();
double dblLine4 = Double.valueOf(line4).doubleValue();
//Assign the values.
this.intWarehouseBItemCount = intLine3;
this.dblTotalValueB = dblLine4;
/**Assign the item count and total value to warehouse C.*/
//Cast.
int intLine5 = Integer.valueOf(line5).intValue();
double dblLine6 = Double.valueOf(line6).doubleValue();
//Assign the values.
this.intWarehouseCItemCount = intLine5;
this.dblTotalValueC = dblLine6;
/**Put the items back into the warehouses arraylists. */
//Add items to warehouse A.
while((lineA = inA.readLine()) != null)
warehouseAList.add(lineA);
//Add items to warehouse B.
while((lineB = inB.readLine()) != null)
warehouseBList.add(lineB);
//Add items to warehouse C.
while((lineC = inC.readLine()) != null)
warehouseCList.add(lineC);
}(this isn't the whole try statement its pretty long) -
Arbitrary waveform generation from large text file
Hello,
I'm trying to use a PXI 6733 card hooked up to a BNC 2110 in a PXI 1031-DC chassis to output arbitrary waveforms at a sample rate of 100kS/s. The types of waveforms I want to generate are generally going to be sine waves of frequencies less than 10 kHz, but they need to be very high quality signals, hence the high sample rate. Eventually, we would like to go up to as high as 200 kS/s, but for right now we just want to get it to work at the lower rate.
Someone in the department has already created for me large text files > 1GB with (9) columns of numbers representing the output voltages for the channels(there will be 6 channels outputting sine waves, 3 other channels with a periodic DC voltage. The reason for the large file is that we want a continuous signal for around 30 minutes to allow for equipment testing and configuration while the signals are being generated.
I'm supposed to use this file to generate the output voltages on the 6733 card, but I keep getting numerous errors and I've been unable to get something that works. The code, as written, currently generates an error code 200290 immediately after the buffered data is output from the card. Nothing ever seems to get enqued or dequed, and although I've read the Labview help on buffers, I'm still very confused about their operation so I'm not even sure if the buffer is working properly. I was hoping some of you could look at my code, and give me some suggestions(or sample code too!) for the best way to achieve this goal.
Thanks a lot,
Chris(new Labview user)Chris:
For context, I've pasted in the "explain error" output from LabVIEW to refer to while we work on this. More after the code...
Error -200290 occurred at an unidentified location
Possible reason(s):
The generation has stopped to prevent the regeneration of old samples. Your application was unable to write samples to the background buffer fast enough to prevent old samples from being regenerated.
To avoid this error, you can do any of the following:
1. Increase the size of the background buffer by configuring the buffer.
2. Increase the number of samples you write each time you invoke a write operation.
3. Write samples more often.
4. Reduce the sample rate.
5. Change the data transfer mechanism from interrupts to DMA if your device supports DMA.
6. Reduce the number of applications your computer is executing concurrently.
In addition, if you do not need to write every sample that is generated, you can configure the regeneration mode to allow regeneration, and then use the Position and Offset attributes to write the desired samples.
By default, the analog output on the device does what is called regeneration. Basically, if we're outputting a repeating waveform, we can simply fill the buffer once and the DAQ device will reuse the samples, reducing load on the system. What appears to be happening is that the VI can't read samples out from the file fast enough to keep up with the DAQ card. The DAQ card is set to NOT allow regeneration, so once it empties the buffer, it stops the task since there aren't any new samples available yet.
If we go through the options, we have a few things we can try:
1. Increase background buffer size.
I don't think this is the best option. Our issue is with filling the buffer, and this requires more advanced configuration.
2. Increase the number of samples written.
This may be a better option. If we increase how many samples we commit to the buffer, we can increase the minimum time between writes in the consumer loop.
3. Write samples more often.
This probably isn't as feasible. If anything, you should probably have a short "Wait" function in the consumer loop where the DAQmx write is occurring, just to regulate loop timing and give the CPU some breathing space.
4. Reduce the sample rate.
Definitely not a feasible option for your application, so we'll just skip that one.
5. Use DMA instead of interrupts.
I'm 99.99999999% sure you're already using DMA, so we'll skip this one also.
6. Reduce the number of concurrent apps on the PC.
This is to make sure that the CPU time required to maintain good loop rates isn't being taken by, say, an antivirus scanner or something. Generally, if you don't have anything major running other than LabVIEW, you should be fine.
I think our best bet is to increase the "Samples to Write" quantity (to increase the minimum loop period), and possibly to delay the DAQmx Start Task and consumer loop until the producer loop has had a chance to build the queue up a little. That should reduce the chance that the DAQmx task will empty the system buffer and ensure that we can prime the queue with a large quantity of samples. The consumer loop will wait for elements to become available in the queue, so I have a feeling that the file read may be what is slowing the program down. Once the queue empties, we'll see the DAQmx error surface again. The only real solution is to load the file to memory farther ahead of time.
Hope that helps!
Caleb Harris
National Instruments | Mechanical Engineer | http://www.ni.com/support
Maybe you are looking for
-
HI all, Iam are working on CRM version 5.0, CIC webclient support package 07, we are creating a employee help desk scenario profile,for which have created a new profile by copying the standard "help desk" profile . while we creating a service ticket
-
In Firefox options I have removed Gmail as the mail to application, and set it to Thunderbird. In Windows I have set Thunderbird to be default. Windows XP and latest update Thuderbird and Firefox.
-
Sql Query - Update Closing Balance
Hi I am trying to write a SQL Query , for the following table , I want to update Closing Balance in the table during Query refresh and it should update Closing Balance. First Row Cl Balance : Op Balance + Receipt - Issue = Cl Balance From Second row
-
Hi All, I require a BDC for CL20N(njoy SAP) transaction to add characteristic value to manufacturing plant for class type 053(ippe node). When I try to record thru SHDB it is exiting from the middle, but when I run the transaction without SHDB its wo
-
A little more info -- the program is running on Windows 8.1, 64 bit OS. I originally purchased the program from Amazon -- could I uninstall and then re-download from there to resolve this? Thanks!