Reading in a file with BufferedReader
I haven't used Java for anything beyond calculations and simulations so my programming skills aren't great.
I'm trying to read in a file which contains scientific data. I want to skip two digits, read 5 into one element of an integer array, skip 14 digits, read 5 into another integer array, read another 5 into a third integer array and then skip to the next line. I've worked out that I can use BufferedReader for this and the skip method is easy enough to understand. But the read(Char[],int,int) method has thrown me. It reads my 5 numbers into 5 elements of a character array.
So how can I get these 5 elements of a character array into one element of an integer array? Or can it not be done? Or is there something similair to BufferedReader that uses int[] instead of char[]?
Let me repost your data with a monospace font, so that the structure is visible:
IF13065 382 101215000+10008904031330IIIaF HZ 647 511aU
V13066 770 8706360-65008904041005IIaD GG 495 200a
IF13067 382 N1212045+11298904041054IIIaF HZ 6471800a
B13068 622 65014200-15008904041429IIaO GG 385 150a
The spaces aren't present in every row of data. It just depends on what astronomical data is needed for that element - (prisms, filters, emulsions etc.)Are the exact positions of the numbers fixed per line? Then do as I suggested:
Read the whole line and use substring() thats much easier to write and understand than trying to do skip() and read().
Similar Messages
-
How to read a text file through BufferedReader
I want to read a text file by BufferedReader, How can I do that? The format of the file as follows:
NAME MAKER YEAR PRICE CONDITION
13 Dead End Drive __ Milton Bradley 1993 $22.00 C09
18 Wheeler Fever __ Donna Lee Ent. 1980 $20.00 C09
how to parse the line from the file to extract the name, maker, year, price and condition.
Thank you first.Look at: stream tutorials,
BufferedReader, InputStreamReader, FileInputStream, StringTokenizer -
How to read the second line in a .txt file with bufferedReader?
hi,
i am not the best in speaking english and programming java :)
so, just try to make sense of my question:
Im using a BufferedReader to read a .txt file.
the .txt file has 5+ different lines, and each line has 6 tokens (separated with ; )
My java file has 6 textFields and each textfield is filled with one of the 6 different tokens.
and my problem is:
I want my buffered reader to read the next line (with 6 new different tokens) by pressing a button.
if somethings not understandable, just ask :)maybe its easier to help me, when i publish my code, so here it is:
(its my version, without Thof's code. Sorry, but the comments are the most in german)
/* userdata.java */
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
import java.util.*;
import java.io.*;
public class userdata extends Frame {
//-----------------------------------KlassenVariablen------------------------------------------------
private JPanel panel = new JPanel ();
String tokId = "";
String tokName= "";
String tokAge= "";
String tokTel= "";
String tokMail= "";
String tokText= "";
BufferedReader br;
String zeile;
StringTokenizer st;
String delim = ";";
//---------Buttons f?r Panel 1-------------------------
Button first = new Button("|< First");
Button back = new Button("< Back");
Button next = new Button("Next >");
Button last = new Button("Last >|");
//---------Buttons f?r Panel 3-------------------------
Button neu = new Button("New");
Button safe = new Button("Safe");
Button refresh = new Button("Refresh");
//--------Labels f?r Panel 2-----------------------------
Label lid = new Label("ID",Label.LEFT);
Label lname = new Label("Name",Label.LEFT);
Label lage = new Label("Age",Label.LEFT);
Label ltel = new Label("Tel.",Label.LEFT);
Label lmail = new Label("E-Mail",Label.LEFT);
Label ltext = new Label("Spruch",Label.LEFT);
Label lub = new Label("Last Button",Label.LEFT);
TextField id = new TextField();
TextField name = new TextField();
TextField age = new TextField();
TextField tel = new TextField();
TextField mail = new TextField();
TextField text = new TextField();
TextField usedbutton = new TextField();
//--------ActionEvent bla sachen eben--------------------
public static void main (String[] args) throws IOException {
userdata wnd = new userdata();
wnd.setVisible(true);
public userdata() throws IOException {
//--------------------------------Layout mit panel bestimmung--------------------------------------
setLayout(new BorderLayout());
JPanel p1 = new JPanel();
JPanel p2 = new JPanel();
JPanel p3 = new JPanel();
add(BorderLayout.NORTH ,p1);
add(BorderLayout.CENTER , p2);
add(BorderLayout.SOUTH , p3);
//-------------------------------Funktionslose Buttons in PANEL 1------------------------------------
p1.add(first);
p1.add(back);
p1.add(next);
p1.add(last);
p1.add(usedbutton);
//--------------------------------Funktionierende Textfelder in PANEL 2------------------------------
Panel labelpanel = new Panel();
p2.setLayout(new GridLayout(7,3));
p2.add(lid);
p2.add(id);
p2.add(lname);
p2.add(name);
p2.add(lage);
p2.add(age);
p2.add(ltel);
p2.add(tel);
p2.add(lmail);
p2.add(mail);
p2.add(ltext);
p2.add(text);
p2.add(lub);
p2.add(usedbutton);
//--------------------------------------Buttons in PANEL 3-----------------------------------------
p3.add(neu);
p3.add(safe);
p3.add(refresh);
//--------------------------------BufferedReader -------------------------------------------------
readData();
//--------------------------------Panel 2 TextField-----------------------------------------------
fillForm();
//================================ActionPerformed==================================================
first.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println ("First");
usedbutton.setText("First");
back.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println ("Back");
usedbutton.setText("Back");
next.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println ("Next");
usedbutton.setText("Next");
last.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println ("Last");
usedbutton.setText("Last");
neu.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println ("New entry");
usedbutton.setText("New");
safe.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
System.out.println ("Now Saving, do not turn off!");
usedbutton.setText("Save");
//-----------------refresh
refresh.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed( ActionEvent e ) {
try{
readData();
}catch( IOException ioe){
System.out.println("Fehler beim lesen aus Datei");
fillForm();
usedbutton.setText("Refresh");
//=============================================================================Button Funktionen!!!
pack();
//--------------------------------WindowsListener hinzuf?gene--------------------------------------
addWindowListener(
new WindowAdapter() {
public void windowClosing(WindowEvent event)
setVisible(false);
dispose();
System.exit(0);
//-----------------------------------readData() - > Buffered Reader in aktion! --------------------
private void readData() throws IOException{
BufferedReader br = new BufferedReader(new FileReader("My .txt File with path"));
String zeile;
StringTokenizer st;
String delim = ";";
zeile = br.readLine();
st = new StringTokenizer(zeile, delim);
st.hasMoreTokens();
//System.out.println (st.nextToken());
tokId = new String(st.nextToken());
tokName = new String (st.nextToken());
tokAge = new String (st.nextToken());
tokTel = new String (st.nextToken());
tokMail = new String (st.nextToken());
tokText = new String (st.nextToken());
//--------------------------fillForm() - > f?llt die TextFelder aus!--------------------------------
private void fillForm(){
id.setText(tokId);
name.setText(tokName);
age.setText(tokAge);
tel.setText(tokTel);
mail.setText(tokMail);
text.setText(tokText);
} -
Reading file with BufferedReader
Hi i have a problem iam trying to make a linked lists, where i read a file and
each word in that file is putt into the list.
but the problem is when i use a while loop and the eadLine() method.
like this
<method >
String word;
try .....
while((word = file.readLine() ) ! =null){
word = file.readLine();
The problem is that readLine() only reads the first word in the file and doesnt make the rest of the list
any suggestions??
here is the rest of the code:
import java.io.*;
class Lister
public static void main(String []args) throws Exception {
Listene l = new Listene();
l.initiate(args);
class Listene {
private BufferedReader file;
Listerr list = new Listerr();
public void initiate(String args[]) throws IOException
String filename =args[0];
String word;
try
file = new BufferedReader(new FileReader(filename));
while( ( word = file.readLine( ) ) != null ){
word = file.readLine();
//System.out.println(word);
list.insert(ord);
shutdown();
catch (FileNotFoundException e)
System.out.println("Minila-filen kan ikke �pnes: " + filename);
public void shutdown()
if (file != null)
try
file.close();
catch (Exception e)
System.out.println("F�r ikke lukket Minila-filen") ;
class Listerr{
Node liste =null;
Node next;
void insert(Object element){
if(liste==null){
liste=new Node(element);
System.out.println("setter inn element: "+element);
else{
Node n = liste;
while(n.neste!=null){
n=n.neste;
n.neste=new Node(element);
System.out.println("setter inn element: "+n.element);
class Node{
Object element;
Node neste;
public Node(Object element2){
element=element2;
neste=null;
}Hi, I assume you are trying to read WORDs seperated by newline. i.e., each WORD occuring in a newline in the input-file. If that is the case, the code you have written should work perfectly. One reason why it may fail is when the newline character inserted by the input-file editor is not the one as listed by System.getProperty("line.separator");
One small change to your code to avoid redundant calls to BufferFileReader::readline() can be done as follows...
String word = null;
try
while( (word = file.readLine()) != null )
list.inert(word);
catch (IOException ex)
//System.out.println("Could not read file: " + filename + ex.getMessage());
} -
*** Reading from a file with tags ***
Hi guys,
I don't know if it is possible, but can you read from a file that contains tags?
For example, say i want to write a simple program that just outputs the details of a person that it reads in from someFile.dat
someFile.dat
<DETAILS>
<NAME> Napolean Solo </NAME>
<ADDRESS> 10 Some Street, SomePlace </ADDRESS>
<PHONE> 33333 </PHONE>
<NAME> Illya Kuryakin </NAME>
<ADDRESS> 12 Some Street, SomeOtherPlace </ADDRESS>
<PHONE> 44444 </PHONE>
</DETAILS>
So what i want is program that outputs to the screen like:
Napolean Solo
10 Some Street, SomePlace
33333
Illya Kuryakin
Is this possible in Java?????
I really appreciate any help that is given,
thanks in advance :)So what i want is program that outputs to the screen
like:
Napolean Solo
10 Some Street, SomePlace
33333
Illya Kuryakin
...If that's all you want (and since a valid xml file has to start with at least <?xml version="1.0"?> so XML is irrelevant to this discussion) then this will generate the output you specify from the imput you provided:import java.io.*;
import java.util.StringTokenizer;
public class SimpleAngleBracketEliminator {
public static void main (String[] args) throws Exception {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
String line;
while ((line=in.readLine())!=null) {
StringTokenizer st = new StringTokenizer(line, "<>");
while (st.hasMoreTokens()) {
st.nextToken();
if (st.hasMoreTokens()) {
System.out.print(st.nextToken().trim());
System.out.println();
}But if you actually want the benefits of real XML, then use a real XML parser.
Pete -
Read an XML file with java: Document to Node conversion
Hello,
I want to read an XML file and convert data into a Node instance because I need this for an XForm application.
My code is:
private Node workstationType;
public Node initModel() {
try {
//This one will hold the results
Document document;
//loading from XML File
String fileName="C:\\documents\\iniForm.xml";
FileInputStream inXML = new FileInputStream(fileName);
BufferedReader in = new BufferedReader(new InputStreamReader(inXML));
document = XMLLoader.loadFromStream(in);
} catch (Exception e) {
System.err.println("ERROR:" + e.getMessage());
e.printStackTrace(System.err);
//Create the node for the root, 'typeOfWorkstation'
workstationType = document.getDocumentElement(); //A
//Return the root node
return (workstationType);
The problem: I can convert Node instance to Document instance (line A)
The error message is: "document cannot be resolved".
How can I do that??
Thank you
SylvainHere is my XMLLoader class:
public class XMLLoader {
public static Document loadFromStream(Reader reader) throws Exception {
//Build a DOM document with the reader
//prepare DOM document
DOMImplementation impl;
DocumentBuilder builder;
try {
// Find the implementation
DocumentBuilderFactory factory =
DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
factory.setValidating(false);
builder = factory.newDocumentBuilder();
impl = builder.getDOMImplementation();
//Read and parse the XML input stream into a DOM document
Document document = builder.parse(new InputSource(reader));
return document;
} catch (IOException ex) {
throw new RuntimeException(
"[XMLLoader.loadFromFile]: Failed loading the InputStream. Root cause: \n"
+ ex);
} catch (Exception ex) {
throw new RuntimeException(
"[XMLLoader.loadFromFile]: Failed to initialize DOM factory. Root cause: \n"
+ ex); -
Issue in reading a binary file, with 'Flatten to String' data.
I'm facing issue while reading a binary file (created using LabVIEW).
I've mentioned everything (issue and method to reproduce it) within the attached VI.
Same vi is attached in 2012 and 8.0 versions.
Regards
I am not allergic to Kudos, in fact I love Kudos.
Make your LabVIEW experience more CONVENIENT.
Solved!
Go to Solution.
Attachments:
Issue in VI.vi 26 KB
Issue in VI (Version 8.0).vi 43 KBmoderator1983 wrote:
crossrulz wrote:
The reading of a string from a binary file stops at a NULL character (0x00). When the first character is 0x00, you are just reading the one character. I would suggest writing to a byte array since you are doing the inverting. And then you can read as a byte array.
crossrulz:
U rocks..!!
you have hit bull's eye...!!
After playing around a little more, I think I might have misinformed you a little. If you explicitly tell it a string, it looks for the string length at the very beginning and reads that length of bytes as a string. It appears that if you implicitly tell it to read a string (not wire the data type) it reads all of the bytes directly, including the length of string you wrote.
Regardless, my advice is the same. You should just write and read using byte array. It is less conversions if you are performing your "encryption".
EDIT: Here's a snippet of the VI I was playing with to figure this out.
There are only two ways to tell somebody thanks: Kudos and Marked Solutions
Unofficial Forum Rules and Guidelines
Attachments:
String Binary File.png 12 KB -
Reading fixed length file with different record types
Hi,
I need to read a fixed-length file with different record types, but the record identifier is in 31st position and not in 1st position.
But if I give 31 as position in File adpater wizard, BPEL takes whole 1-31 as identifier.
How we need to read such files.
Thanks
Ravdeephi ,
u cannot use the default wzard for this
use some thing like this nxsd:lookAhead="30" nxsd:lookFor="S"have a look at the below link it has some examples
http://download.oracle.com/docs/cd/B31017_01/integrate.1013/b28994/nfb.htm -
Reading a csv file with a large number of columns
Hello
I have been attempting to read data from large csv files with 38 columns by reading a line using readline and scanning the linebuffer using scan.
The file size can be up to 100 MB.
Scan does not seem support the large number of fields.
Any suggestions on reading the 38 comma separated fields. There is one header line in the file.
Thanks
Solved!
Go to Solution.see if strtok() is useful http://www.elook.org/programming/c/strtok.html
-
Reading fixed position files with File Adapter
Hi !
I'm trying to use the file adapter to read a file with data in fixed positions .
I cannot get it to work, I'm getting :
[Line=3, Col=133] Expected "${eol}" at the specified position in the native data, while trying to read the data for "element with name Hours", using "style" as "array" and "cellSeparatedBy" as "${eol}", but not found.
Ensure that "${eol}", exists at the specified position in the native data.
and don't understand what the problem is.Sorry I didn't reply sooner.
If you are only interested in the first 133 characters then as you stated you need to put in a dummy filler at the end.
The file adapter is not as smart as you think. What is does is reads the string in a stream, so it gets its command and reads the stream until it hits it, then it gets the next command.
In your situation you said read 1 - 133 thinking it would ignore the other characters in the line. In reality what happens is that it reads the first 133 characters. Assuming that it wasn't looking for a end of line it would then read the next 133 characters. This would include the character you want to ignore, so your pattern would fail.
Good way to think about it is to apply the rules as if you are reading the file your self. In your mind you say read these characters then I want to ignore all the others in the row. You have to tell the file adapter to do the same.
Hope this explains.
cheers
James -
I can't read a pdf file with apercu
I've updated apercu a few days ago. Since I did it, I can't read pdf file anymore. what can I do ?
Can you please share the file with us at [email protected]? Also, can you please confirm that you are viewing the PDF in the Adobe Reader app rather than an app like dropbox, Mail or Safari?
-
Reading a WPS files with Pages
I was sent an email file attachment in a .WPS format. Is there a utility or simple trick to open and read these types of files with Pages?
Welcome to Apple Discussions
You might be able to convert it free at this site into a Word file that Pages can open:
http://www.zamzar.com/
Walt -
Read from spreadsheet file with multiple delimiters
Is there a way to specify multiple delimitors in the read from spreadsheet file vi? I have a file that i need to read in that contains both space and comma delimitors and would like to read that data into an array using both delimitors (or not and). Below is the data I'm trying to read.
;attenuator data table
att00: db 000h,015h,017h,035h,03Ch,03Eh,03Eh,05Ch,05Eh,05Eh
att10: db 07Ch,07Eh,07Fh,09Dh,09Fh,09Fh,0BDh,015h,017h,035h
att20: db 03Eh,03Eh,05Ch,05Ch,05Eh,07Ch,07Ch,07Eh,09Dh,09Dh
att30: db 09Fh,0BDh,000h,000h,000h,002h,002h,002h,002h,003h
att40: db 021h,021h,021h,021h,021h,023h,023h,023h,023h,023h
att50: db 041h,041h,048h,048h,048h,04Ah,04Ah,04Ah,04Ah,068h
att60: db 068h,068h,068h,068h,068h,06Ah,06Bh,06Bh,06Bh,089h
att70: db 089h,089h,089h,08Bh,08Bh,08Bh,08Bh,0A9h,0A9h,0A9h
att80: db 0A4h,0A6h,0A6h,0A6h,0A6h,0C4h,0C4h,0C4h,0C4h,0C6h
att90: db 0C6h,0C6h,0C6h,0E4h,0E4h,0E5h,0E5h,0E7h,0E7h,0E7h
END
I'm looking to just read in the data adjust the hex values and then save the data in the exact form which I read it in. If read from spreadsheet file can not recognize multiple delimiters that is all I need to know. I do not want to spend time reading it in using a single delimitor and doing a bunch of string manipulation. I'm also working with LabView 8.5 if that makes a difference.You should use "scan string for tokens", and wire an array of delimiters.
One nice behavior is the fact that consecutive delimiters are contracted into one (by default), so e.g. if your delimiters is an array containing a space and a comma, a sequence of three spaces and a comma would still count as one delimiter.
For some ideas, have a look at my old example here:
http://forums.ni.com/ni/board/message?board.id=170&message.id=192847#M192847
LabVIEW Champion . Do more with less code and in less time . -
Read an XML file with namespace items
I'm a beginner with XML and for the first time i have to read a file with columns.
I have try this code, but the result is always the same: no rows selected.
variable xml_response varchar2(4000)
BEGIN
:xml_response :=
<?xml version="1.0" encoding="UTF-8"?>
<ROOT xmlns="http://www.post.ch/schemas/dfu/2006/20/Report11">
<Sender SenderID="1618" SenderName="Laurastar SA" ReportCreated="20141120053155">
<Provider ProviderID="539ADAEE-FF18-49F8-84B8-B90232CBCC61" ProviderName="Pakete">
<Data>
<Item SendingID="a68f0007-c4df-4ecb-8dfe-d6da6c2e0cda" ItemID="5430243" IdentCode="993314781300000254" />
<Item SendingID="beba5a0e-6363-42f1-aeb5-51c5171ed032" ItemID="5430241" IdentCode="993314781300000255" />
<Item SendingID="beba5a0e-6363-42f1-aeb5-51c5171ed032" ItemID="5430241" IdentCode="993314781300000255" />
</Data>
</Provider>
</Sender>
</ROOT>';
END;
SELECT x.*
FROM XMLTable(
'/ROOT'
passing xmltype(:xml_response)
columns
ReportCreated varchar2(30) path 'Sender/@ReportCreated'
, SendingID varchar2(50) path 'Sender/Provider/Data/Item/@SendingID'
, ItemID varchar2(30) path 'Sender/Provider/Data/Item/@ItemID'
, IdentCode varchar2(30) path 'Sender/Provider/Data/Item/@IdentCode'
) x
I could not found what is wrong.I could not found what is wrong.
Two things are wrong :
1) Lack of namespace declaration
2) You're trying to project repeating nodes into a single row
This should work :
SELECT x1.ReportCreated
, x2.*
FROM XMLTable(
XMLNamespaces(default 'http://www.post.ch/schemas/dfu/2006/20/Report11')
, '/ROOT/Sender'
passing xmltype(:xml_response)
columns
ReportCreated varchar2(30) path '@ReportCreated'
, items xmltype path 'Provider/Data/Item'
) x1
, XMLTable(
XMLNamespaces(default 'http://www.post.ch/schemas/dfu/2006/20/Report11')
, 'Item'
passing x1.items
columns
SendingID varchar2(50) path '@SendingID'
, ItemID varchar2(30) path '@ItemID'
, IdentCode varchar2(30) path '@IdentCode'
) x2 -
How To read an XML file with JDom
I have read through some tutorials after installing JDom on how to read an existing XML file and I was confused by all of them. I simply want to open an XML file and read one of the node's content. Such as <username>john doe</username> this way I can compare values with what the user has entered as their username. I am not sure were to start and I was hoping someone could help me out.
I know that this seems like an insecure way to store login information but after I master opening and writing XML files with JDom I am going to use AES to encrypt the XML files.Here is a test program for JDom and XPath use considering your XML file is named "test.xml" :import org.jdom.input.*;
import org.jdom.xpath.*;
public class JDomXPath {
public static void main(String[] args) {
SAXBuilder saxBuilder = new SAXBuilder("org.apache.xerces.parsers.SAXParser");
try {
org.jdom.Document jdomDocument = saxBuilder.build("test.xml");
org.jdom.Element usernameNode = (org.jdom.Element)XPath.selectSingleNode(jdomDocument, "//username");
System.out.print(usernameNode.getText());
} catch (Exception e) {
e.printStackTrace();
}(tested with Eclipse)
Maybe you are looking for
-
Detect Displays no longer works after upgrade
Mac Mini 2009 - two weeks old, came with Leopard. Took some doing, but have it hooked up to Sony Bravia 40" LCD via Mini-Display port to VGA adaptor. Detect Display worked fine, connected at High Def resolution. Upgraded to Snow Leopard 10.6.1 today,
-
Is there a way to add jar file in my program
sorry to botter you, but i really need help for this, i really dont know how to do it. i have my prog taht i want to put in jar file, that cause no problem, but my program isnt fully functionnal because he use a jar file (my driver to acces my databa
-
Can't login to Directory Service Control Center 6
After installition of Sun JES 5 Directory Server (OS Solaris SPARC 9) i'm trying to login to DSCC. I provide username admin and a password for admin. But after clicking the LogIn Button I see a message Authentification error. IWhen I explore a Direct
-
I have windows 8 and I have the most updated version of Itunes, my iphone 4s connects, but nothing plays from my itunes all items have the cloud next to it, and they are dithered out
-
Keeping focus in the viewable window of a scroll pane
I have many text fields and text areas inside a scroll pane. When I use tab to cycle through these boxes the focus goes out of the viewable window rather then the scroll pane moving to follow the focus. Is it possible for the scroll pane to follow th