Help with inputting from text file.
Okay, been struggling with this for a couple days and I could really use some help.
I need to input text one line at a time into String[] text, I'm reading from a file called "textfile.txt" and I want to store the result
String[] text = { first_line, second_line, third_line, fourth_line...........etc}
This works now:
//code
String[] test =
{ "1 2, 3 4, 5 6"
for (int i = 0; i < test.length; i++) {
Graph g = new Graph(test);
// end code
But that of course reads "1 2, 3 4, 5 6" from the code, and not from a text file. My StringTokenizer looks for a "," and makes that the end of the token, so I need to add a "," after each line as well.
In other words, I need to turn the text file :
"1 2
3 4
5 6"
into :
"1 2, 3 4, 5 6"
These are just numbers to test of course, the real text file I need to input has hundreds of lines.
Any help would be appreciated, thank you.
I'm fairly lost. I understand that you need to read a file, and that file contains many lines which each contain a pair of numbers. But then you say (a) that you need to create an array of Strings and (b) that you need to store the result. And there's this mysterious StringTokenizer in there as well. You seem to be suggesting some solution that concatenates all the lines together, with commas between them, so that the StringTokenizer can then go through that concatenation and break it apart into the original pieces.
Okay, here's some code that reads through a file and makes an array of Strings, one entry per line:BufferedReader in = new BufferedReader(new FileReader("textfile.txt"));
String data = null;
List inputs = new ArrayList();
while ((data = in.readLine()) != null) {
inputs.add(data);
in.close();
String[] lines = new String[0];
lines = (String[]) inputs.toArray(lines);Untested, and exception handling and so forth omitted. I leave it to you to decide what to do with that array of Strings.
PC²
Similar Messages
-
Hello
I would like to incorporate code into this to allow the script I found on the internet to pull input from a txt file and then wait for the script to end before using the next entry in the text file and run until all entries in the text file have been used.
Any help would be great thx.
Jason
' Get Options from user
GetOptions
If (bInvalidArgument) Then
WScript.Echo "Invalid Arguments" & VbCrLf
bDisplayHelp = True
End If
If (bDisplayHelp) Then
DisplayHelp
Else
If (bCheckVersion) Then
CheckVersion
End If
If (strComputer = "") Then
strComputer = InputBox("What Computer do you want to document (default=localhost)","Select Target",".")
End If
If (strComputer <> "") Then
' Run the GatherWMIInformation() function and return the status
' to errGatherInformation, if the function fails then the
' rest is skipped. The same applies to GatherRegInformation
' if it is successful we place the information in a
' new word document
errGatherWMIInformation = GatherWMIInformation()
If (errGatherWMIInformation) Then
If (bDoRegistryCheck) Then
errGatherRegInformation = GatherRegInformation
End If
GetWMIProviderList
Else
WScript.Quit(999)
End If
If (bHasMicrosoftIISv2) Then ' Does the system have the WMI IIS Provider
GatherIISInformation
End If
SystemRolesSet
If (errGatherWMIInformation) Then
Select Case strExportFormat
Case "word"
PopulateWordfile
Case "xml"
PopulateXMLFile
End Select
End If
End If
End IfUnfortunately the script is too long to be posted but can be found at
http://sydiproject.com/download/and is called Server v.2.3. I have also contacted the author and made the suggestion I
asked about.
Jason
I do not know which script you had in mind but the one I looked at had 1,600 lines of code. As you say, posting it here would be inappropriate. At the same time it is unrealistic to ask for help for such a large script. Asking the author is one option. The
other option would be to identify the module you wish to modify, analyse it until you fully understand it, modify it so that you can run it in a stand-alone manner, then post your question here. You will probably find that you can answer the question yourself
after analysing the code! -
JTable - Help with updating a Text File
Hi all,
I've been fighting this for a few days. I am trying to update a Text File with my JTable.... Displaying the data works great but when I try to edit a cell/field on the gui, I'm bombing out...... My text fiel is a small user control file with Id, Name,
Date, etc etc with the fields delimited with a "|".... I have built an Abstract Data Model (see below).... and I think my problem is in the setValueAt method.......
Thanks so much in advance!!!!
Mike
code:
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.io.*;
import java.util.*;
public class DataFileTableModel extends AbstractTableModel {
protected Vector data;
protected Vector columnNames ;
protected String datafile;
public DataFileTableModel(String f){
datafile = f;
initVectors();
public void initVectors() {
String aLine ;
data = new Vector();
columnNames = new Vector();
try {
FileInputStream fin = new FileInputStream(datafile);
BufferedReader br = new BufferedReader(new InputStreamReader(fin));
// extract column names
StringTokenizer st1 =
new StringTokenizer(br.readLine(), "|");
while(st1.hasMoreTokens())
columnNames.addElement(st1.nextToken());
// extract data
while ((aLine = br.readLine()) != null) {
StringTokenizer st2 =
new StringTokenizer(aLine, "|");
while(st2.hasMoreTokens())
data.addElement(st2.nextToken());
br.close();
catch (Exception e) {
e.printStackTrace();
public int getRowCount() {
return data.size() / getColumnCount();
public int getColumnCount(){
return columnNames.size();
public String getColumnName(int columnIndex) {
String colName = "";
if (columnIndex <= getColumnCount())
colName = (String)columnNames.elementAt(columnIndex);
return colName;
public Class getColumnClass(int columnIndex){
return String.class;
public boolean isCellEditable(int rowIndex, int columnIndex) {
return true;
public Object getValueAt(int rowIndex, int columnIndex) {
return (String)data.elementAt( (rowIndex * getColumnCount()) + columnIndex);
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
Vector rowVector=(Vector)data.elementAt(rowIndex);
rowVector.setElementAt(aValue, columnIndex);
fireTableCellUpdated(rowIndex,columnIndex);
// return;
}No, the DefaultDataModel does not update the physical data file. It is just used to store the data as you type in the table cells.
The code from above is used to read data from a file and populate the DataModel.
Now you need to write another routine that will take the data from the DataModel and write it to your file. I have never actually done this but I think the code would be something like:
int rows = table.getModel().getRowCount();
int columns = table.getModel().getColumnCount();
// Write column headers
for (int j = 0; j < columns; j++)
TableColumn column = table.getColumnModel().getColumn(j);
Object o = column.getHeaderValue();
writeToFile( o.toString() + "|" );
writeToFile( "\n" );
// Write each row
for (int i = 0, i < rows; i++)
for (int j = 0, j < columns; j++)
Object o = table.getValueAt(i, j);
writeToFile( o.toString + "|" );
writeToFile( "\n" );
}If you need to update the file whenever data in a cell changes, then you could extend the DefaultTableModel and override the setValueAt() method to also write the contents of the DataModel to a file. But this is a lot of overhead since it rewrite the entire file for every cell change. -
Help with downloading pdf/text files itunes
Hi,
I am trying to download and view the text/pdf files from this link: https://itunes.apple.com/us/course/statistics-110-probability/id502492375 (files 1, 4, 11 and so on.. )
However, I am not able to open the text/pdf file from the downloads window on itunes. I use itunes on mac.
I would appreciate your help.
Thanks
Parangparangsaraf wrote:
Hi,
I am trying to download and view the text/pdf files from this link: https://itunes.apple.com/us/course/statistics-110-probability/id502492375 (files 1, 4, 11 and so on.. )
However, I am not able to open the text/pdf file from the downloads window on itunes. I use itunes on mac.
You don't open it in the download window.
Select iTunes U in the left sidebar.
If you don't see the left sidebar, iTunes menu View > View sidebar. -
Need help with query from .csv file
I am trying to import a csv file with only 1 column in it.
The column will only contain a 9 digit ID number. I want to read
the file then use the contents to query a table to get the names
and other information and display it. Here is what I have so far:
<cffile action="read" file="#form.FiletoUpload#"
variable="csvfile">
<cfloop index="index" list="#csvfile#">
<cfquery name="massimport" datasource="data1">
SELECT * FROM IDTable
WHERE CardNumber = ('#csvfile#')
</cfquery>
</cfloop>
<cfoutput>#Name# #ID# #Site#</cfoutput>
I get no errors but I am not getting any results. Just a
blank page. Does anyone know how to query directly from a csv
import? Thanks.You need to convert your file to a list somehow. Not sure if
this is the most efficient way but, you can use the cfhttp tag to
produce a query. Then your where clause becomes,
where cardnumber in (#quotedvaluelist(query.column)#)
and you won't need a loop. -
Help with input output .txt files!
Hi i'm a student and totally new to programming. I need the program to read a .txt file and then output it:
import java.io.*;
import java.util.*;
public class Reading{
public static void main(String[] args)throws Exception{
Scanner scanner = new Scanner(new File(args[0]));
while(scanner.hasNext()){
System.out.println(scanner.next());
scanner.close();
and
import java.io.*;
public class Writing{
public static void main(String[] args)throws Exception{
String outputFile = args[0];
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
for(int i = 0; i < 100; i++){
writer.println(i * i);
writer.close();
How would i merge these together? I also changed the command line to java Reading Input.txt but it wont run on DrJava on my computer or laptop and i get an error? How do i then store the strings into an arraylist and iterate throught the arraylist to reverse the strings?
Please help.You could do this...
import java.io.*;
import java.util.*;
public class FileIO2
public static void main(String argsp[])
String readfile="ajr.txt";
String writefile="ajr2.txt";
try{
read(readfile);
write(writefile);
catch(Exception e)
{e.printStackTrace();}
public static void read(String filename) throws Exception
Scanner scanner = new Scanner(new File(filename));
while(scanner.hasNext()){
System.out.println(scanner.next());
scanner.close();
public static void write(String filename) throws Exception
String outputFile = filename;
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter(outputFile)));
for(int i = 0; i < 100; i++){
writer.println(i * i);
writer.close();
} -
Read from text file takes very long after the first time
Dear LabVIEW experts,
I'm having a problem with read from text file. I'm trying to read only every nth line of a file for a preview with this sub vi:
I seems to work well the first time I do it. The loop takes almost no time to execute an iteration.
Then when I load the same file again with exactly the same settings one iteration takes around 50ms.
Subsequent attempts seem to always take the longer execution time.
Only when I restart the calling vi it will be quick for one file.
When executing the sub vi alone it is always quick, but I don't see how the main vi (too complex to post here) could obstruct the execution of the sub vi.
I don't have a the file opened elsewhere in the main vi, I don't use too much memory...
Right now I don't now where to look. Does anyone have an idea?
Regards
Florian
Solved!
Go to Solution.I don't know the LabVIEW internals here, but I would think that it is quite possible that closing a file opened for read/write access writes a new copy of the file to disk, or at least checks the file in order to make sure a new file does not have to be written.
Therefore, if your main VI calls this subVI sequentially (you don't give any information about the place of this subVI in the main VI), you are actually looking at a close (check/write) -> open operation for any time you call it, as opposed to a simple open operation the first time. If you were to open the file for simple read access (since that's all you do), it should work fast every time because there is no need to check to see if it has changed.
Cameron
To err is human, but to really foul it up requires a computer.
The optimist believes we are in the best of all possible worlds - the pessimist fears this is true.
Profanity is the one language all programmers know best.
An expert is someone who has made all the possible mistakes.
To learn something about LabVIEW at no extra cost, work the online LabVIEW tutorial(s):
LabVIEW Unit 1 - Getting Started
Learn to Use LabVIEW with MyDAQ -
Read from Text File - Help Bug?
Hi - I am currently working on LV8 and I think that there is some misunderstanding potential in the help file. To be more exact in the help to the "Read From Text File" VI.
The description for "count":
" ... If count is <0, the function reads the entire file. The
default is –1, which indicates to read a single line if you placed a checkmark
next to the Read Lines shortcut menu item and to read the
entire file if you removed the checkmark next to the item. "
If count is lower than zero, the function reads the entire file. That sounds clear to me.
The default is -1, which indicates to read a single line if you placed a checkmark next to the "Read Lines" shortcut menu item. Now what? Does it read a single line or the whole file?
.. and to read the entire file if you removed the checkmark next to the item. I thought it reads the whole file if I use -1 ?
the VI itself behaves as I'd expect it to:
* If I place a checkmark next to Read Lines and put -1, I get an array containing the lines
* If I remove the checkmark, I get only a single string item.
Now where is the error? Is the VI not working properly or only the description a little bit ... strange ??hein??
?what?
Both you guys lost me..
And I drink coffee without sugar (being sweet enough, already)
Here is what I get from Context Help on the Read From Text File:
Read from Text File
Reads a specified number of characters or lines from a byte stream file. By default, this function reads all characters from the text file. Wire an integer value to count to specify how many individual characters you want to read starting with the first character. Right-click the function and place a checkmark next to the Read Lines option in the shortcut menu to read individual lines from the text file. When you select the Read Lines option in the shortcut menu, wire an integer value to the count input to specify how many individual lines you want to read from the file starting with the first line. Enter a value of -1 in count to read all characters and lines from the text file.
Humm.
New feature (again).. If you select checkmark the Read Lines option, it will not send the text to a sting indicator, as shown in the attached image. If selected, then it's expecting to write lines to an array of strings... WHY??? I don't know.. I'll ask..
Strange... LV8 is full of mysteries...
RayR
Attachments:
bad write file.JPG 33 KB
more bad write file.JPG 12 KB -
Read from Text File Detailed Help need Clean-up
This is probably well known and nobody has bothered fixing it but the detailed Help of the "Read from Text File" function is sort of ambiguous:
- statement 1: refnum out is the refnum of the file that the function read. You can wire this output to another file function, depending on what you want to do with the file. The default is to close the file if it is referenced by a file path or selected from the file dialog box. If file is a refnum or if you wire refnum out to another function, LabVIEW assumes that the file is still in use until you close it.
- statement 2: If you wire a path to file, the function opens the file before reading from it and closes it afterwards.
I have found statement 1 to be correct, which makes statement 2 incomplete (and sort of tautological in the sense that 1) you expect LabVIEW to open the file before reading from it if you provide a path instead of a refnum... and 2) if you use a path input to file AND use the refnum out for some other function, the file is NOT closed, as correctly stated in statement 1).
Just sayin' ...X,
It deeply concerns me that you would take my response to mean indifference. I certainly had no intention to belittle what you had to say. On the contrary, I took this up with the concerned team, and had a small discussion. If you say that what someone says on this forum is of lesser or no value to National Instruments, you could not be more wrong. It defeats the whole purpose of this public forum.
My point was not that it is not an issue, it certainly seems to be. Please be rest assured that even if it does not look like it from the outside, each comment however big or small is taken back to our workplaces and some thoughts poured over it.
On the whole, I recognise that I had a role to play in this misunderstanding of tone, and I sincerely apologise.
Warm Regards,
Prashanth N
National Instruments -
How to create PDF from text file with specific layout?
I wanted to create the pdf from text file in specific layout - Landscape orientation and JIS B3 Page size while at Adobe Acrobat Pro.
In past, I could do a right click on a text file (desktop area) and select print to print out the document into .pdf BUT only if I set the Adobe PDF to Landscape and JIS B3 Page size BEFORE. And I could only do 15 text documents at once.
I wanted to see if I could do the create the pdf from text file with specific layout in Adobe Acrobat without having to go to Control Panel to preset the Adobe PDF to specific layout at every time. I would have to set Adobe PDF back to normal layout after I'm done with these pdf print outs. I do lots of pdfs in normal layout. Sometimes I would forget to do that.
So, How do I do that?No such luck. It would output the contents in letter size even in JIS B3 Page layout at MS word.
Is there a script or action where I could set the orientation and page size before creating PDF on these text files? -
Why does Read from Text file default to array of 9 elements
I am writing to a text file starting with a type def. cluster (control) of say 15 dbl numeric elements, that works fine I open the tab-delimited text file and all of the elements appear in the file. However when I read from the same text file back to the same type def. cluster (indicator), the read from text file defaults to 9 elements?? Is there a way to control how many elements are read from the file. This all works great when I initially use a cluster of 9 elements and read back to a cluster of 9 elements.
Solved!
Go to Solution.From the LabVIEW Help: http://zone.ni.com/reference/en-XX/help/371361G-01/glang/array_to_cluster/
Converts a 1D array to a cluster of elements of the same type as the array elements. Right-click the function and select Cluster Size from the shortcut menu to set the number of elements in the cluster.
The default is nine. The maximum cluster size for this function is 256.
Aside: so, how many times has this question been asked over the years? -
How to open saved files using 'read from text file' function
Hi everyone, I am having a hard time trying to solve the this particular problem ( probably because I am a newb to lanbview ). Anyway , I am able to save the acquired waveforms by using the 'Write to text file' icon. I did manually modify the block diagram of the 'Write to text file' icon and create the correct number of connector so as to make my program work. But now I have no idea on how to modify the block diagram of the 'Read from text file' block diagram to make my program 'open' my saved waveforms. Or i do not have to modify anything from the block diagram of the 'Read from text file'? Can anyone teach/help me connect up? Do i need the build array on the "open" page?
Here are some screenshots on part of my program
let me know if you guys would need more information / screenshots thank you!
Attachments:
ss_save.jpg 94 KB
ss_open.jpg 94 KB
modified_writetotextfile.jpg 99 KBOhmy, thanks altenbach. oh yeah i forgot about those sub VIs. will upload them now. Was rather demoralized after reading the comments and really struck me on how weak i'm at on labview really hope to get this done. But of course i have to study through and see how it works. Actually i am going to replace those 'signal generators sub vi' with ThoughtTechonology's sample code so i can obtain data waveforms real-time using Electrocardiography (ECG) ,Electromyography (EMG ) and Electroencephalography (EEG) hopefully i can find out how to connect the sample code.
( ps . cant connect it now unless my program is working otherwise labview will crash )
( p.s.s the encoder of my biofeedback trainer already acts as an DAQ so i wont need to place an DAQ assistant in my block diagram i suppose )
The sample code of ThoughtTechnology is named as attachment.ashx.vi. too bad i cant use it and present it as my project
Attachments:
frequency detactor.vi 53 KB
signal generator.vi 13 KB
attachment.ashx.vi 40 KB -
LabVIEW for ARM 2009 Read from text file bug
Hello,
If you use the read from text file vi for reading text files from a sdcard there is a bug when you select the option "read lines"
you cannot select how many lines you want to read, it always reads the whole file, which cause a memory fault if you read big files!
I fixed this in the code (but the software doesn't recognize a EOF anymore..) in CCGByteStreamFileSupport.c
at row 709 the memory is allocated but it tries to allocate to much (since u only want to read lines).
looking at the codes it looks like it supposed to allocated 256 for a string:
Boolean bReadEntireLine = (linemode && (cnt == 0));
if(bReadEntireLine && !cnt) {
cnt = BUFINCR; //BUFINCR=256
but cnt is never false since if you select read lines this is the size of the file!
the variable linemode is also the size of the file.. STRANGE!
my solution:
Boolean bReadEntireLine = (linemode && (cnt > 0)); // ==
if(bReadEntireLine) { //if(bReadEntireLine && !cnt) {
cnt = BUFINCR;
and now the read line option does work, and reads one line until he sees CR or LF or if the count of 256 is done.
maybe the code is good but the data link of the vi's to the variables may be not, (cnt and linemode are the size of the file!)
count should be the number of lines, like chars in char mode.
linemode should be 0 or 1.
Hope someone can fix this in the new version!
greets,
Wouter
Wouter.
"LabVIEW for ARM guru and bug destroyer"I have another solution, the EOF works with this one.
the cnt is the bytes that are not read yet, so the first time it tries to read (and allocate 4 MB).
you only want to say that if it's in line mode and cnt > 256 (BUFINCR) cnt = BUFINCR
the next time cnt is the value of the bytes that are not read yet, so the old value minus the line (until CR LF) or if cnt (256) is reached.
with this solution the program does not try to allocate the whole file but for the max of 256.
in CCGByteStreamFileSupprt.c row 705
if(linemode && (cnt>BUFINCR)){
cnt = BUFINCR;
don't use the count input when using the vi in line mode. count does not make sense, cnt will be the total file size. also the output will be an array.
linemode seems to be the value of the file size but I checked this and it is just 0 or 1, so this is good
update: damn it doesn't work!
Wouter.
"LabVIEW for ARM guru and bug destroyer" -
Read from text file vi won't read file...
I am very new to LV programming so I hope you forgive any stupid mistakes I am making. I am using Ver. 8.2 on an XP machine.
I have a small program that stores small data sets in text files and can update them individually or read and update them all sequentially, sending the data out a USB device. Currently I am just using two data sets, each in their own small text file. The delimiter is two commas ",,".
The program works fine as written when run in the regular programming environment. I noticed, however, as soon as I built it into a project that the one function where it would read each file sequentially to update both files the read from text file vi would return an empty data set, resulting in blank values being written back into the file. I read and rewrite the values back to the text file to place the one updated field (price) in it'sproper place. Each small text file is identified and named with a 4 digit number "ID". I built it twce, and get the same result. I also built it into an installer and unfortunately the bug travelled into the installation as well.
Here is the overall program code in question:
Here is the reading and parsing subvi:
If you have any idea at all what could cause this I would really appreciate it!
Solved!
Go to Solution.Hi Kiauma,
Dennis beat me to it, but here goes my two cents:
First of all, it's great to see that you're using error handling - that should make troubleshooting a lot easier. By any chance, have you observed error 7 when you try to read your files and get an empty data set? (You've probably seen that error before - it means the file wasn't found)
If you're seeing that error, the issue probably has something to do with this:
Relative paths differ in an executable. This knowledge base document sums it up pretty well. To make matters more confusing, if you ever upgrade to LabVIEW 2009 the whole scheme changes. Also, because an installer contains the executable, building the installer will always yield the same results.
Lastly, instead of parsing each set of commas using the "match pattern" function, there's a function called "spreadsheet string to array" (also on the string palette) that does exactly what you're doing, except with one function:
I hope this is helpful...
Jim -
Charting data from text file in LabVIEW 5.1 for Windows
I am having some difficulties trying to figure out how to plot a chart with
data from a file. I would like to be able to read data from a text file
into a chart using LabVIEW 5.1 for Windows. I have looked in the help
within the program and online. I have also looked in the user manual and
the book "LabVIEW for Everyone". Could you please give me specific
instructions on how I would construct the program to be able to do this.
Thank you.Hi Ellie,
It depends on how data is stored in that txt file. Usually you load the data into an array either using or , the array if necessary and send it to the graph indicator in required form. If you want a more detailed answer, send me a sample data file ([email protected]).
Maybe you are looking for
-
Crystal Reports XII and Dynamic Images
From an ASP.NET 2.0 web page I am executing a Crystal Reports that creates a photo album(actually a student directory) of from several dozen images to about 700. The images are pkulled from a file system directory. The problem I am having is that fr
-
Ipod not being recognised, but with a twist
Hi, My ipod nano 5th Gen is not being recognised on my computer. It is now being recognised by the computer itself sometimes, but not itunes. However, when I plug my ipod into my partners laptop, its fine. More to the point, when they plug their's in
-
System-Roles Assignments Groups Lost in Reporting Services 2012
Hello, hope someone can help me with this: I moved a Report Server database from 2008 to 2012. Y did the backup/restore for Reportserver and ReportServerTempDB, Also y backing up the Encryption Keys and restore it in the new 2012. But When I ope
-
ESATA/USB-Combo-Port on T520 connect to external Harddrive case
Hello. I have a eSATA/USB-Combo-Port on a T520. I think there are cables to connect a 2,5" Harddisk direct to the Port with only one cable for eSATA and Power. I am looking for an external case for a 2,5" Harddisk that have a USB-Port (to connect to
-
Sync not syncing playlists correctly
New user. Ran into considerable problems syncing with itunes before discovering the ipad doesn't support playlist folders so I created new playlists not in folders and tried syncing them over usb. itunes shows it has synced everything, but from the