473,706 Members | 2,578 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Read a file

16 New Member
My code
[

public class Student{
private String lastName;
private String firstName;
private String middleName;
private int sid;
private double units;
private String Programs;


public Student(){
this( "", "", "", 0, 0.0, "");
}

public Student (String lastName, String firstName, String middleName, int sid, double units, String Programs )
{
//setLastName(las tName);
setFirstName(fi rstName);
setMiddleName(m iddleName);
setsid(sid);
setunits(units) ;
setPrograms(Pro grams);

}

public void setLastName(Str ing lastName){
lastName = lastName;
}

public String getLastName(){
return lastName;
}

public void setFirstName(St ring firstName){
firstName = firstName;
}

public String getFirstName(){
return firstName;
}

public void setMiddleName(S tring middleName){
middleName = middleName;
}

public String getMiddleName() {
return middleName;
}

public void setsid(int sid){
sid = sid;
}
public int getsid(){
return sid;
}


public void setunits(double units){
units = units;
}


public double getunits()
{
return units;
}


public void setPrograms(Str ing Programs){
Programs = Programs;
}

public String getPrograms(){
return Programs;
}

}

]
Another class
[

import java.io.File;
import java.io.IOExcep tion;
import java.util.Scann er;

public class Roaster {

Student st[] = new Student[100];

/* public static void copyLines() throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;

try {
inputStream =
new BufferedReader( new FileReader("roa ster.txt"));

for(i=0;i<no.of lines;i++)
{
addstudent(fir,
}
outputStream =
new PrintWriter(new FileWriter("cha racteroutput.tx t"));

String l;
while ((l = inputStream.rea dLine()) != null) {

outputStream.pr intln(l);
}
} finally {
if (inputStream != null) {
inputStream.clo se();
}
if (outputStream != null) {
outputStream.cl ose();
}
}
}*/

public void addStudentfromF ile() throws IOException
{
Scanner inputStream = null;
try {
inputStream =
new Scanner(new File("roaster.t xt"));
int noofstu = 1;

while (inputStream.ha sNext()) {

String temp = inputStream.nex t();
String[] name = null;
name = temp.split(",") ;
/* System.out.prin tln(name[0]);
System.out.prin tln(name[1]);
System.out.prin tln(inputStream .next());

System.out.prin tln(inputStream .nextInt());

System.out.prin tln(inputStream .nextDouble());
System.out.prin tln(inputStream .next());*/
st[noofstu-1] = new Student(name[0], name[1], inputStream.nex t(),inputStream .nextInt() , inputStream.nex tDouble(),input Stream.next());
noofstu++;
}
} finally {
if (inputStream != null) {
inputStream.clo se();
}

}

}

public int getStudentno(){
//getStudent = new Student;
return st.length;

}


public static void main(String[] args) {


}
}
]
Another class for testing
[
import java.io.Buffere dInputStream;
import java.io.Buffere dReader;
import java.io.DataInp utStream;
import java.io.File;
import java.io.FileInp utStream;
import java.io.FileRea der;
import java.io.IOExcep tion;

public class RoasterTest {

public static void main (String[] args) throws Exception{
File RoasterTest = new File( "roaster.tx t" );
if ( RoasterTest.exi sts() )
{
// Create the buffered reader for reading the file
BufferedReader inFile = new BufferedReader( new FileReader( RoasterTest ) );



// Get the first line of the file
String line = inFile.readLine ();

// If line is not end of file continue
while ( line != null )
{
// Create a StringTokenizer with a colon sign as a delimiter
java.util.Strin gTokenizer st =
new java.util.Strin gTokenizer( line, ":" );

// Display the content of the first token
System.out.prin t( " Name: " + st.nextToken() );

// Display the total number of tokens remaining this string
int numScores = st.countTokens( );

// Initialize the sum to zero
int sum = 0;

// Get each score, add it to the sum and print it
for ( int i=1; i <= numScores; i++ )
{
int score = Integer.parseIn t( st.nextToken() );
sum += score;
}

// Display the average score for this student
System.out.prin tln( " average = " + sum/numScores );

// Read next line of the file
line = inFile.readLine ();

} // end while not at end of file

// Close the BufferedReader
inFile.close();

// try {
// RoasterTest.clo ne();
// } catch (IOException ioe) {

} // end if the grade file doesn't exist

}

}

]

My test class does not read student class or roaster class .. I know I am missing something but I am loss
Oct 16 '07 #1
8 2448
dmjpro
2,476 Top Contributor
My code
[

public class Student{
private String lastName;
private String firstName;
private String middleName;
private int sid;
private double units;
private String Programs;


public Student(){
this( "", "", "", 0, 0.0, "");
}

public Student (String lastName, String firstName, String middleName, int sid, double units, String Programs )
{
//setLastName(las tName);
setFirstName(fi rstName);
setMiddleName(m iddleName);
setsid(sid);
setunits(units) ;
setPrograms(Pro grams);

}

public void setLastName(Str ing lastName){
lastName = lastName;
}

public String getLastName(){
return lastName;
}

public void setFirstName(St ring firstName){
firstName = firstName;
}

public String getFirstName(){
return firstName;
}

public void setMiddleName(S tring middleName){
middleName = middleName;
}

public String getMiddleName() {
return middleName;
}

public void setsid(int sid){
sid = sid;
}
public int getsid(){
return sid;
}


public void setunits(double units){
units = units;
}


public double getunits()
{
return units;
}


public void setPrograms(Str ing Programs){
Programs = Programs;
}

public String getPrograms(){
return Programs;
}

}

]
Another class
[

import java.io.File;
import java.io.IOExcep tion;
import java.util.Scann er;

public class Roaster {

Student st[] = new Student[100];

/* public static void copyLines() throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;

try {
inputStream =
new BufferedReader( new FileReader("roa ster.txt"));

for(i=0;i<no.of lines;i++)
{
addstudent(fir,
}
outputStream =
new PrintWriter(new FileWriter("cha racteroutput.tx t"));

String l;
while ((l = inputStream.rea dLine()) != null) {

outputStream.pr intln(l);
}
} finally {
if (inputStream != null) {
inputStream.clo se();
}
if (outputStream != null) {
outputStream.cl ose();
}
}
}*/

public void addStudentfromF ile() throws IOException
{
Scanner inputStream = null;
try {
inputStream =
new Scanner(new File("roaster.t xt"));
int noofstu = 1;

while (inputStream.ha sNext()) {

String temp = inputStream.nex t();
String[] name = null;
name = temp.split(",") ;
/* System.out.prin tln(name[0]);
System.out.prin tln(name[1]);
System.out.prin tln(inputStream .next());

System.out.prin tln(inputStream .nextInt());

System.out.prin tln(inputStream .nextDouble());
System.out.prin tln(inputStream .next());*/
st[noofstu-1] = new Student(name[0], name[1], inputStream.nex t(),inputStream .nextInt() , inputStream.nex tDouble(),input Stream.next());
noofstu++;
}
} finally {
if (inputStream != null) {
inputStream.clo se();
}

}

}

public int getStudentno(){
//getStudent = new Student;
return st.length;

}


public static void main(String[] args) {


}
}
]
Another class for testing
[
import java.io.Buffere dInputStream;
import java.io.Buffere dReader;
import java.io.DataInp utStream;
import java.io.File;
import java.io.FileInp utStream;
import java.io.FileRea der;
import java.io.IOExcep tion;

public class RoasterTest {

public static void main (String[] args) throws Exception{
File RoasterTest = new File( "roaster.tx t" );
if ( RoasterTest.exi sts() )
{
// Create the buffered reader for reading the file
BufferedReader inFile = new BufferedReader( new FileReader( RoasterTest ) );



// Get the first line of the file
String line = inFile.readLine ();

// If line is not end of file continue
while ( line != null )
{
// Create a StringTokenizer with a colon sign as a delimiter
java.util.Strin gTokenizer st =
new java.util.Strin gTokenizer( line, ":" );

// Display the content of the first token
System.out.prin t( " Name: " + st.nextToken() );

// Display the total number of tokens remaining this string
int numScores = st.countTokens( );

// Initialize the sum to zero
int sum = 0;

// Get each score, add it to the sum and print it
for ( int i=1; i <= numScores; i++ )
{
int score = Integer.parseIn t( st.nextToken() );
sum += score;
}

// Display the average score for this student
System.out.prin tln( " average = " + sum/numScores );

// Read next line of the file
line = inFile.readLine ();

} // end while not at end of file

// Close the BufferedReader
inFile.close();

// try {
// RoasterTest.clo ne();
// } catch (IOException ioe) {

} // end if the grade file doesn't exist

}

}

]

My test class does not read student class or roaster class .. I know I am missing something but I am loss
Use Code Tags.
Please post the file content.

Debasis Jana
Oct 16 '07 #2
Jromero
16 New Member
My code
[

public class Student{
private String lastName;
private String firstName;
private String middleName;
private int sid;
private double units;
private String Programs;


public Student(){
this( "", "", "", 0, 0.0, "");
}

public Student (String lastName, String firstName, String middleName, int sid, double units, String Programs )
{
//setLastName(las tName);
setFirstName(fi rstName);
setMiddleName(m iddleName);
setsid(sid);
setunits(units) ;
setPrograms(Pro grams);

}

public void setLastName(Str ing lastName){
lastName = lastName;
}

public String getLastName(){
return lastName;
}

public void setFirstName(St ring firstName){
firstName = firstName;
}

public String getFirstName(){
return firstName;
}

public void setMiddleName(S tring middleName){
middleName = middleName;
}

public String getMiddleName() {
return middleName;
}

public void setsid(int sid){
sid = sid;
}
public int getsid(){
return sid;
}


public void setunits(double units){
units = units;
}


public double getunits()
{
return units;
}


public void setPrograms(Str ing Programs){
Programs = Programs;
}

public String getPrograms(){
return Programs;
}

}

]
Another class
[

import java.io.File;
import java.io.IOExcep tion;
import java.util.Scann er;

public class Roaster {

Student st[] = new Student[100];

/* public static void copyLines() throws IOException {
BufferedReader inputStream = null;
PrintWriter outputStream = null;

try {
inputStream =
new BufferedReader( new FileReader("roa ster.txt"));

for(i=0;i<no.of lines;i++)
{
addstudent(fir,
}
outputStream =
new PrintWriter(new FileWriter("cha racteroutput.tx t"));

String l;
while ((l = inputStream.rea dLine()) != null) {

outputStream.pr intln(l);
}
} finally {
if (inputStream != null) {
inputStream.clo se();
}
if (outputStream != null) {
outputStream.cl ose();
}
}
}*/

public void addStudentfromF ile() throws IOException
{
Scanner inputStream = null;
try {
inputStream =
new Scanner(new File("roaster.t xt"));
int noofstu = 1;

while (inputStream.ha sNext()) {

String temp = inputStream.nex t();
String[] name = null;
name = temp.split(",") ;
/* System.out.prin tln(name[0]);
System.out.prin tln(name[1]);
System.out.prin tln(inputStream .next());

System.out.prin tln(inputStream .nextInt());

System.out.prin tln(inputStream .nextDouble());
System.out.prin tln(inputStream .next());*/
st[noofstu-1] = new Student(name[0], name[1], inputStream.nex t(),inputStream .nextInt() , inputStream.nex tDouble(),input Stream.next());
noofstu++;
}
} finally {
if (inputStream != null) {
inputStream.clo se();
}

}

}

public int getStudentno(){
//getStudent = new Student;
return st.length;

}


public static void main(String[] args) {


}
}

import java.io.Buffere dInputStream;
import java.io.Buffere dReader;
import java.io.DataInp utStream;
import java.io.File;
import java.io.FileInp utStream;
import java.io.FileRea der;
import java.io.IOExcep tion;

public class RoasterTest {

public static void main (String[] args) throws Exception{
File RoasterTest = new File( "roaster.tx t" );
if ( RoasterTest.exi sts() )
{
// Create the buffered reader for reading the file
BufferedReader inFile = new BufferedReader( new FileReader( RoasterTest ) );



// Get the first line of the file
String line = inFile.readLine ();

// If line is not end of file continue
while ( line != null )
{
// Create a StringTokenizer with a colon sign as a delimiter
java.util.Strin gTokenizer st =
new java.util.Strin gTokenizer( line, ":" );

// Display the content of the first token
System.out.prin t( " Name: " + st.nextToken() );

// Display the total number of tokens remaining this string
int numScores = st.countTokens( );

// Initialize the sum to zero
int sum = 0;

// Get each score, add it to the sum and print it
for ( int i=1; i <= numScores; i++ )
{
int score = Integer.parseIn t( st.nextToken() );
sum += score;
}

// Display the average score for this student
System.out.prin tln( " average = " + sum/numScores );

// Read next line of the file
line = inFile.readLine ();

} // end while not at end of file

// Close the BufferedReader
inFile.close();

// try {
// RoasterTest.clo ne();
// } catch (IOException ioe) {

} // end if the grade file doesn't exist

}

}

]

This is my code
Oct 16 '07 #3
dmjpro
2,476 Top Contributor
Look, have look at "ObjectInputStr eam","ObjectOut putStream" and "Serializat ion" in java.
Have a look through Google.
Any further problem, please post here.

Debasis Jana
Oct 16 '07 #4
Jromero
16 New Member
I still don't get it please help me
Oct 16 '07 #5
dmjpro
2,476 Top Contributor
I still don't get it please help me
Look,
"ObjectInputStr eam" for object reading from a stream,
and "ObjectOutputSt ream" for object writing for a strean.
Now the Object should implement "Serializab le" interface.

Have a look at this sample code ...............

Expand|Select|Wrap|Line Numbers
  1. ObjectOutputStream o = new OutjectOutputStream(new FileOutputStream("test.dat"));
  2. Student s = new Student(/*Some data goes here*/);
  3. o.writeObject(s);
  4. .
  5. .
  6. ObjectInputStream i = new ObjectInputStream(new FileInputStream("test.dat"));
  7. Student _s = (Student)i.readObject();
  8. //now access the _s object.
  9.  
Your Student class should be like this .......
Expand|Select|Wrap|Line Numbers
  1. class Student implements Serializable
  2. {
  3.  //your code goes here
  4. }
  5.  
Debasis Jana
Oct 16 '07 #6
Jromero
16 New Member
The
Code[
ObjectOutputStr eam o = new ObjectOutputStr eam(new FileOutputStrea m("roaster.txt" ));
Student s = new Student("String lastName, String firstName, String middleName, int sid, double units, String Programs", null, null, 0, 0, null);
o.writeObject(s );

ObjectInputStre am i = new ObjectInputStre am(new FileInputStream ("roaster.txt") );
Student _s = (Student)i.read Object();
// now access the _s object.

]
Goes in Roaster class
Oct 16 '07 #7
dmjpro
2,476 Top Contributor
You got your code worked?

Actually I forgot to close the streams.
See the code carefully.
Expand|Select|Wrap|Line Numbers
  1. ObjectOutputStream o = new OutjectOutputStream(new FileOutputStream("test.dat"));
  2. Student s = new Student(/*Some data goes here*/);
  3. o.writeObject(s);
  4. o.close();
  5. .
  6. .
  7. ObjectInputStream i = new ObjectInputStream(new FileInputStream("test.dat"));
  8. Student _s = (Student)i.readObject();
  9. i.close();
  10. //now access the _s object.
  11.  
Your Student class should be like this .......
Expand|Select|Wrap|Line Numbers
  1. class Student implements Serializable
  2. {
  3.  //your code goes here
  4. }
  5.  

Debasis Jana
Oct 16 '07 #8
Jromero
16 New Member
I am still having problems I don't where to put the object stream
Oct 17 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

10
5323
by: Yang Li Ke | last post by:
Hi guys! I have some datas that I must check everytime a visitor comes to my site What is better to do: 1- Read data from a file or 2- Read data from a mysql db Thank you
10
2283
by: ZafT | last post by:
Thanks in advance for any tips that might get me going in the right direction. I am working on a simple exercise for school that is supposed to use read to read a file (about 10 MB). I am supposed to change the buffer size and see how this affects the read time. In other words, the buffer is supposed to limit how much of the file gets read per call, and cause some change in speed. I am supposed to do the same with fread as well, but...
1
6762
by: cnu | last post by:
My program generates a log file for every event that happens in the program. So, I open the file and keep it open till the end. This is how I open the file for writing: <CODE> public CLogHandler() { this.m_fsLog = new FileStream(strTodaysLogFile, System.IO.FileMode.Append, System.IO.FileAccess.Write, System.IO.FileShare.Read); this.m_swLog = new StreamWriter(this.m_fsLog);
4
2740
by: ESPN Lover | last post by:
Below is two snippets of code from MSDN showing how to read a file. Is one way preferred over the other and why? Thanks. using System; using System.IO; class Test { public static void Main()
8
23903
by: a | last post by:
I have a struct to write to a file struct _structA{ long x; int y; float z; } struct _structA A; //file open write(fd,A,sizeof(_structA)); //file close
5
3303
by: lovecreatesbea... | last post by:
The condition at line 31 is added to check if the program finished to read the whole file. Is it needed and correct? Thank you. #include <fstream> #include <iostream> #include <string> using namespace std; int read(string filename, int last_pos) {
0
5787
by: lovecarole | last post by:
hi, i am the student who should write a program about reading wav file and do the DFT. actually i don't know how to read data of the wav song and save it into the array... if i want to read 17640 every times., and i set byte read=new byte, i have the wav format paper, but i don't know how to read the data correctly into the byte array, and used for doing DFT.... here's my code, and i am little hurry...thanks for the helps first~
6
32915
by: Thomas Kowalski | last post by:
Hi, currently I am reading a huge (about 10-100 MB) text-file line by line using fstreams and getline. I wonder whether there is a faster way to read a file line by line (with std::string line). Is there some way to burst read the whole file and later "extract" each line? Thanks in advance, Thomas Kowalski
9
7385
by: flebber | last post by:
I was working at creating a simple program that would read the content of a playlist file( in this case *.k3b") and write it out . the compressed "*.k3b" file has two file and the one I was trying to read was maindata.xml . I cannot however seem to use the gzip module correctly. Have tried the program 2 ways for no success, any ideas would be appreciated. Attempt 1 #!/usr/bin/python
2
5449
by: Kevin Ar18 | last post by:
I posted this on the forum, but nobody seems to know the solution: http://python-forum.org/py/viewtopic.php?t=5230 I have a zip file that is several GB in size, and one of the files inside of it is several GB in size. When it comes time to read the 5+GB file from inside the zip file, it fails with the following error: File "...\zipfile.py", line 491, in read bytes = self.fp.read(zinfo.compress_size) OverflowError: long it too large to...
0
8773
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8692
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9276
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
7897
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6613
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4442
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4705
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2495
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2084
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.