How do I read from a file and store the information in an array?
Here is my problem:
I am going to have to use a bufferedReader to read a file containing information on 10 vehicles. And after I read that file I want to store the info in Vehicle [] V.
Where should I start?
Thanks
Steve
Thank you for the quick response.
As of right now our code is the same. Now I have to "parse" the information. What exactly do you mean?
My code is as follows:
while((str = br.readLine()) != null)
String[] tokenArray = str.split(" ");
for(int i = 0; i < tokenArray.length; i++)
System.out.print(" Token: " + tokenArray);
System.out.println("\n");
Is that what you mean by parsing?
I am not quite sure what e slpit(" ") is doing. Is there a better way?
And just to make sure I am understanding my own code, I am storing the information from the br in tokenArray. Followed by a series of print statements which output the info.Correct?
Thanks again,
Steve
Similar Messages
-
Read from .txt file and output the content as two arrays
I am using the contoured move to control the x-y stage. The trajectory datas for x and y axis are generated using my interpolation program and it is stored in a .txt file as two columns. What I want to do is read .txt file and output the content of this file as two arrays. Is there anyone has any ideas? Thanks, the .txt file is attached.
Attachments:
R.75.txt 172 KBHi Awen,
This is quite easy to do, you can merely use the "read from spreadsheet file" function to get a 2D array (2 columns and n rows) and then use the index array function to get whatever row/colums you want..
Hope the attached VI helps you
When my feet touch the ground each morning the devil thinks "bloody hell... He's up again!"
Attachments:
read sprdsheet file.vi 27 KB -
(Urgent help needed) how to read txt file and store the data into 2D-array?
Hi, I have a GUI which allow to choose file from the file chooser, and when "Read file" button is pressed, I want to show the array data into the textarea.
The sample data is like this followed:
-0.0007 -0.0061 0.0006
-0.0002 0.0203 0.0066
0 0.2317 0.008
0.0017 0.5957 0.0008
0.0024 1.071 0.0029
0.0439 1.4873 -0.0003
I want my program to scan through and store these data into 2D array.
However for some reason, my source code issues errors, and I don't know what's wrong with it, seems to have a problem in StringTokenizer though. Can anybody help me?
Thanks in advance.
import java.io.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.StringTokenizer;
public class FileReduction1 extends JFrame implements ActionListener{
// GUI features
private BufferedReader fileInput;
private JTextArea textArea;
private JButton openButton, readButton,processButton,saveButton;
private JTextField textfield;
private JPanel pnlfile;
private JPanel buttonpnl;
private JPanel buttonbar;
// Other fields
private File fileName;
private String[][] data;
private int numLines;
public FileReduction1(String s) {
super(s);
// Content pane
Container cp = getContentPane();
cp.setLayout(new BorderLayout());
// Open button Panel
pnlfile=new JPanel(new BorderLayout());
textfield=new JTextField();
openButton = new JButton("Open File");
openButton.addActionListener(this);
pnlfile.add(openButton,BorderLayout.WEST);
pnlfile.add(textfield,BorderLayout.CENTER);
readButton = new JButton("Read File");
readButton.addActionListener(this);
readButton.setEnabled(false);
pnlfile.add(readButton,BorderLayout.EAST);
cp.add(pnlfile, BorderLayout.NORTH);
// Text area
textArea = new JTextArea(10, 100);
cp.add(new JScrollPane(textArea),BorderLayout.CENTER);
processButton = new JButton("Process");
//processButton.addActionListener(this);
saveButton=new JButton("Save into");
//saveButton.addActionListener(this);
buttonbar=new JPanel(new FlowLayout(FlowLayout.RIGHT));
buttonpnl=new JPanel(new GridLayout(1,0));
buttonpnl.add(processButton);
buttonpnl.add(saveButton);
buttonbar.add(buttonpnl);
cp.add(buttonbar,BorderLayout.SOUTH);
/* ACTION PERFORMED */
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals("Open File")) getFileName();
if (event.getActionCommand().equals("Read File")) readFile();
/* 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);
int result = fileChooser.showOpenDialog(this);
// If cancel button selected return
if (result == JFileChooser.CANCEL_OPTION) return;
if (result == JFileChooser.APPROVE_OPTION)
fileName = fileChooser.getSelectedFile();
textfield.setText(fileName.getName());
if (checkFileName()) {
openButton.setEnabled(false);
readButton.setEnabled(true);
// Obtain selected file
/* READ FILE */
private void readFile() {
// Disable read button
readButton.setEnabled(false);
// Dimension data structure
getNumberOfLines();
data = new String[numLines][];
// Read file
readTheFile();
// Output to text area
textArea.setText(data[0][0] + "\n");
for(int index=0;index < data.length;index++)
for(int j=1;j<data[index].length;j++)
textArea.append(data[index][j] + "\n");
// Rnable open button
openButton.setEnabled(true);
/* GET NUMBER OF LINES */
/* Get number of lines in file and prepare data structure. */
private void getNumberOfLines() {
int counter = 0;
// Open the file
openFile();
// 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();
catch(IOException ioException) {
JOptionPane.showMessageDialog(this,"Error reading File",
"Error 5: ",JOptionPane.ERROR_MESSAGE);
closeFile();
System.exit(1);
/* READ FILE */
private void readTheFile() {
// Open the file
int row=0;
int col=0;
openFile();
System.out.println("Read the file");
// Loop through file incrementing counter
try {
String line = fileInput.readLine();
while (line != null)
StringTokenizer st=new StringTokenizer(line);
while(st.hasMoreTokens())
data[row][col]=st.nextToken();
System.out.println(data[row][col]);
col++;
row++;
closeFile();
catch(IOException ioException) {
JOptionPane.showMessageDialog(this,"Error reading File",
"Error 5: ",JOptionPane.ERROR_MESSAGE);
closeFile();
System.exit(1);
/* CHECK FILE NAME */
/* Return flase if selected file is a directory, access is denied or is
not a file name. */
private boolean checkFileName() {
if (fileName.exists()) {
if (fileName.canRead()) {
if (fileName.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);
/* FILE HANDLING UTILITIES */
/* OPEN FILE */
private void openFile() {
try {
// Open file
FileReader file = new FileReader(fileName);
fileInput = new BufferedReader(file);
catch(IOException ioException) {
JOptionPane.showMessageDialog(this,"Error Opening File",
"Error 4: ",JOptionPane.ERROR_MESSAGE);
System.out.println("File opened");
/* CLOSE FILE */
private void closeFile() {
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");
/* MAIN METHOD */
/* 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);
Java.lang.NullpointException
at FileReductoin1.readTheFile <FileReduction1.java :172>
at FileReductoin1.readFile <FileReduction1.java :110>
at FileReductoin1.actionPerformed <FileReduction1.java :71>
.1) Next time use the CODE tags. this is way too much unreadable crap.
2) The problem is your String[][] data.... the only place I see you do anything approching initializing it is
data = new String[numLines][];I think you want to do this..
data = new String[numLines][3];anyway that's why it's blowing up on the line
data[row][col]=st.nextToken(); -
Reading from XML file and updating the table ????
Hi
I have package which reads the hier.XML file and does Update inserts into the 5 tables
i have table called MAIN_tbl with the column cur_date.
The package kicks if this cur_date is one day less than the hier.XML file DT.
Currently i m manually checking this date's to make sure the Main_tbl cur_date is n sync with
hier.XML file DT.
for example :- hier.xml file DT is "20091020" then main_table cur_date should be 10/19/2009
in order to kicks of the pakage.
what i m looking to do ??
compare the hier.xml DT with the main_table cur_date,
if cur_date is -1(Preivous day) of hier.xml DT then run hier_pkg(Package)
if not then update main_table cur_date to -1(previous day) of the hier.xml DATE
Then later write the above logic to update the main_table in a procedure, and
then call the package from the procedure.
below are the top few lines of the hier.XML file which is relevant to the one which we are trying to do
<?xml version = '1.0'?>
<HIER_POSTING num ="111" HIER_TYP="CD" DT="20091020" Global="Y">
FYI : The hier.XML file is located in UNIX space.
How do i accomplish this. any idea ????
Thank you so much in advance. For giving a thought on this problem!!!Any thought on this guys ???
Thanks!! -
How to extract data from xml file and store that data inti data base table
Hii All
I have one table that table contains one column that column contain an XML file
I want to extract data from that XML file and want to store that extracted data into an other table.
That xml file has different different values
I want to store that values into table in diff diff columnsHi,
I am also facing the same problem.I have a .xml file and i need to import the data into the custom table in oracle database.
Can you please let me know if you know the solution how to do it in oracle apps.
Thanks, -
Read from a file and execute the statement
Hi
I have a .sql file that contains insert statements.
I would like to open the file, read a statement and execute it using a procedure.
Can sombody help me out?> I have a .sql file that contains insert statements.
I would like to ...<snipped> ... execute it ...<snipped>...
Go to SQL*Plus and type in "start <your file name>" ?
If the goal is to insert those records, and using a procedure is less important.
Regards,
Rob. -
How can I read from a file line by line?
Hi!
Could someone post some code or explain how can I read from a file, and want I to read a line each time. How can I go to line number N?
Thankshi,
u can try this:
try {
// open text file
BufferedReader in = new BufferedReader(new FileReader(fileName));
String line=in.readLine();
while((line=in.readLine()) != null) {
System.out.println(line);
}The go to line number N i m not so sure.
Cheers
Jerry -
How to read the data from Excel file and Store in XML file using java
Hi All,
I got a problem with Excel file.
My problem is how to read the data from Excel file and Store in XML file using java excel api.
For getting the data from Excel file what are all the steps i need to follow to get the correct result.
Any body can send me the code (with java code ,Excel sheet) to this mail id : [email protected]
Thanks & Regards,
Sreenu,
[email protected],
india,If you want someone to do your work, please have the courtesy to provide payment.
http://www.rentacoder.com -
Dear all,
I want to use Labview to process a data.
Now I have a array in a text file.
this array is very very big. which is at least row*col = 6 * 100000;
the column size always 6,
but the row size is ramdom, some times is very big, like bigger than 65535,
when I use "read from measurement file express.vi" to read this file, the array I could get always 6*5339, I don't know why. the column size is always 5339.
and then I delete the 1st row of the array and then write into a txt file via "write measurement file express. vi", it takes a very long time. almost computer has no response. after a while, no file was creat to record the data.
is there an efficient way to process such big data file and store the processed file into a new file
thank you very much
Jack
Message Edited by weichengatech on 03-09-2006 12:00 AMHello,
There’s no real efficient way to read the file if you don’t
know exactly how many rows of data you have.
Your going to just have to read a row at a time and add the results to
the end of an array (granted for the clever programmers there are some more
efficient ways to do this than just with ‘build array’). I would start by asking you how much
information you know about the file and what the exact structure of it is (i.e.
is it a binary file, a tab delimited file, or a LVM file)? Could you provide a screenshot of the code
you are running? If you provide a little more information on the file structure
we might be able to contribute some additional information.
Look forward to hearing back from you-
Travis M
LabVIEW R&D
National Instruments -
How to read from excel file and write it using implicit jsp out object
our code is as below:Please give us proper solution.
we are reading from Excel file and writing in dynamicaly generated Excel file.it is writing but not as original excel sheet.we are using response.setContentType and response.setHeader for generating pop up for saveing the original file in to dynamically generated Excel file.
<%@ page contentType="application/vnd.ms-excel" %>
<%
//String dLoadFile = (String)request.getParameter("jspname1");
String dLoadFile = "c:/purge_trns_nav.xls" ;
File f = new File(dLoadFile);
//set the content type(can be excel/word/powerpoint etc..)
response.setContentType ("application/msexcel");
//get the file name
String name = f.getName().substring(f.getName().lastIndexOf("/") + 1,f.getName().length());
//set the header and also the Name by which user will be prompted to save
response.setHeader ("Content-Disposition", "attachment; filename="+name);
//OPen an input stream to the file and post the file contents thru the
//servlet output stream to the client m/c
FileInputStream in = new FileInputStream(f);
//ServletOutputStream outs = response.getOutputStream();
int bit = 10;
int i = 0;
try {
while (bit >= 0) {
bit = in.read();
out.write(bit) ;
} catch (IOException ioe) { ioe.printStackTrace(System.out); }
out.flush();
out.close();
in.close();
%>If you want to copy files as fast as possible, without processing them (as the DOS "copy" or the Unix "cp" command), you can try the java.nio.channels package.
import java.nio.*;
import java.nio.channels.*;
import java.io.*;
import java.util.*;
import java.text.*;
class Kopy {
* @param args [0] = source filename
* args [1] = destination filename
public static void main(String[] args) throws Exception {
if (args.length != 2) {
System.err.println ("Syntax: java -cp . Kopy source destination");
System.exit(1);
File in = new File(args[0]);
long fileLength = in.length();
long t = System.currentTimeMillis();
FileInputStream fis = new FileInputStream (in);
FileOutputStream fos = new FileOutputStream (args[1]);
FileChannel fci = fis.getChannel();
FileChannel fco = fos.getChannel();
fco.transferFrom(fci, 0, fileLength);
fis.close();
fos.close();
t = System.currentTimeMillis() - t;
NumberFormat nf = new DecimalFormat("#,##0.00");
System.out.print (nf.format(fileLength/1024.0) + "kB copied");
if (t > 0) {
System.out.println (" in " + t + "ms: " + nf.format(fileLength / 1.024 / t) + " kB/s");
} -
How can one read a Excel File and Upload into Table using Pl/SQL Code.
How can one read a Excel File and Upload into Table using Pl/SQL Code.
1. Excel File is on My PC.
2. And I want to write a Stored Procedure or Package to do that.
3. DataBase is on Other Server. Client-Server Environment.
4. I am Using Toad or PlSql developer tool.If you would like to create a package/procedure in order to solve this problem consider using the UTL_FILE in built package, here are a few steps to get you going:
1. Get your DBA to create directory object in oracle using the following command:
create directory TEST_DIR as ‘directory_path’;
Note: This directory is on the server.
2. Grant read,write on directory directory_object_name to username;
You can find out the directory_object_name value from dba_directories view if you are using the system user account.
3. Logon as the user as mentioned above.
Sample code read plain text file code, you can modify this code to suit your need (i.e. read a csv file)
function getData(p_filename in varchar2,
p_filepath in varchar2
) RETURN VARCHAR2 is
input_file utl_file.file_type;
--declare a buffer to read text data
input_buffer varchar2(4000);
begin
--using the UTL_FILE in built package
input_file := utl_file.fopen(p_filepath, p_filename, 'R');
utl_file.get_line(input_file, input_buffer);
--debug
--dbms_output.put_line(input_buffer);
utl_file.fclose(input_file);
--return data
return input_buffer;
end;
Hope this helps. -
How can I read an audio file and brodcast it using NI RFSG?
Hi everybody,
I'm designing a wireless audio signal simulation system that will read an audio signal from a file and modulate the signal using NI 5671 RFSG, then broadcast it to be received at an NI 5660 RFSA.
All I need is some guidance from you guys. Some related examples would be of great help since I'm a new user of NI hardwares and software.
Thanks in advance.
Muslim,
Communication Engineering Student,
International Islamic University Malaysia.Hi,
I’m going to
help here since Paul is out of the office, so far you have been able to use
Paul’s example to generate a signal from a Wav File, right? I have a question:
why did you combine some of the parts of the (fm-modulation) with the generate
FM signal from WAV file if the example Paul attached is already modulating the
signal?
I have another question on the part
that you are stuck when reading the file, do you want to play it back through
your speakers or you just want to be able to see the array of samples? Have you
seen the example “MT niRFSA Demodulate FM.vi”? And if so why it does not help? Here
is another example for FM modulation: Sound File Frequency
Modulated Generation using NI-567x I would like to let you know that all
those examples Paul and I are giving you are located at our website most are
free and you may find them yourself; if you have the necessary drivers and
toolkits installed you should be good to go. “The examples
available do not show what I'm searching for” What are you
searching for? What type of analysis do you need to perform?
Remember
that in the RFSA part of your project what you are going to be receiving will
be an array that contains all the points of your data not a WAV file. I will suggest trying to
run both FM example the RFSG and RFSA with no modification for a better
understanding of what is happening.
I hope it helps
Jaime Hoffiz
National Instruments
Product Expert
Digital Multimeters and LCR Meters -
Read a property file and store it in a hashmap
Hi,
I have tried to read a property file and store it in a hashmap. The property-names should be stored in keys and the property-values (after = symbol) in values of the hashmap. any ideas? Is it possible to do this?mandy2001ir wrote:
yes, but I need the hashmap for another reason. Actually I'm trying to use the properties file to have a dynamic hachmap. I don't want to change the code anytime I want to put a value in the hashmap. therefor I write the "keys" and "values" in a property file and change the property file. That's the reasn why we have property files, isn't it?What's a "dynamic hashmap"? There's no other kind! Whenever someone starts bandying around the word "dynamic" in contexts like this, it usually means there's a simple solution to their problem, that they haven't yet considered, or mistakenly don't believe is applicable to them, because of this "unique" need for something "dynamic". Trust me, you just need to load the file using a Properties object, and you're done. Properties extends Hashtable, which is virtually the same thing as a HashMap. Properties does exactly what you want it to. it's the very reason the class exists
Have you even looked at the javadoc for java.util.Properties yet? I'm betting not, because if you had, you'd know exactly what I meant. And since you haven't, I'm at a bit of a loss as to how you can so easily dismiss the class as useless, despite existing to do exactly what you need -
How to execute unix command through odi and store the result in table
I have to reconcile if data is loaded in table from csv file or not . I have to create a oracle data integrator package/interface/procedure to execute unix command to count number of rows in the csv files and store the count result in a table then i have to query the loaded table and count number of rows there and store in the table and have to compare is counts are same or not, Please assist me how to make package/interface/procedure to execute unix command and store result in oracle table.
Thanks in AdvanceUse ODI OS command tool in the ODI package.
create an interface in ODI using LKM File to Sql and the output file generated with the csv file's row count as a source and the db table(where the count needs to be stored) as a target -
Hi guys,
I have in my application a subvi which i use to save the configuration of application. I create one file with the last saved configuration, and i would like to open this values and that i could to modify this indicator value, but i cant since to modify i need 'numeric control' and to read the data from file i need 'numeric indicator '...
I thought, use a numeric control and use the values from file to the default values, but i didnt get to find the property node to adjust it. is it possible? or any different way to get it....??
Also, i attached the capture file.. i would like the program DOESNT SHOW the question of
replace the file!!. i would like directly replace the file when i push save.
Thanks, i attached the vi.
Attachments:
options.vi 43 KB
config.cnf 1 KB
capture.GIF 43 KBHi Dennis,
Your 'write to sreadshhet mod' suprime the dialog of replace file or not!, i want when i push save, it show the dialog input name of file and show the default sim000 but when i push this sim000 and this file already exist, then show the dialog to replace or not, if i replace Ok not problem, but when i push cancel replace it shows error eof!!!.
Your file, only remove this dialog and only replace the file directly.
i put the capture, when i choose the file to save and the program say to me this file exist and it give me the option of replace or not,i want when i push cancel replace it continues running without get error.
is it possible?.
Thanks.
Regards, Fonsi.
Attachments:
capture.GIF 71 KB
example.vi 40 KB
Maybe you are looking for
-
How can I select a date to view in Calendar while I am in month view?
I am looking at month view in Calendar on my iPad. I touch a date. Intuitively, I expect that date to open up in Day or Week view, but it doesn't! On my iphone, it works just fine. Am I missing something? How can I select a date to view while in Mont
-
Why do we use Setup tables in LO
Hi All, Can any body tell me that Why do we use Setup tables in LO. Plz reply back me on [email protected] Regards, Kiran
-
I have PSE9 and a Nikon d5100 Camera. Can't get PSE to accept 5100 raw files.
I have set up to use iphoto to store my psotos and externally edit my files in PSE. Works fine with jpeg files but raw files will not transfer. Get message that PSE will not accept. I think that PSE9 will accept wit an upgrade Camera Raw Plug in 6.4.
-
Hello i have a problem with a game on game center can you help me?
hello i have a problem with a game on game center can you help me?
-
Entering data into Reports-WebDB2.2
Hi, I am trying to enter html into the add text section ("Help Text")of the report. However, the information that i am entering is defaulting to the centre when it is being displayed. i have tried adding html tags <Align> to align the data to the lef