473,385 Members | 1,640 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes and contribute your articles to a community of 473,385 developers and data experts.

Reading and Writing files

13,262 8TB
The program below simply reads a file called FileTest1.java(itself) and prints it to the console

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. import java.util.Scanner;
  4. import java.io.*;
  5. class FileTest1 {
  6.  public static void main(String args[]) {
  7.   Scanner inputFile = null;
  8.   try {
  9.    inputFile = new Scanner(new File("FileTest1.java"));
  10.    while(inputFile.hasNext()) {
  11.     System.out.println(inputFile.next());
  12.    }
  13.  
  14.   }
  15.   catch(FileNotFoundException fNFE) {
  16.    System.out.println("The file was not found");
  17.   }
  18.   finally {
  19.    inputFile.close();
  20.   }
  21.  
  22.  } 
  23.  
  24. }
  25.  
  26.  
  27.  
Two methods of the Scanner class were used here hasNext and next.
You should be able to see what these methods are doing here if not then you can check with the Scanner page on sun's Java API.
This is the recommended way of reading a file these days.

To write to a file, use the FileWriter class wrapped in a BufferedWriter

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. public static void writeFile(String fileName) {
  4.  BufferedWriter br = null;
  5.  try {
  6.   br = new BufferedWriter(new FileWriter(fileName));
  7.   String[] semiFinals = {"Australia", "West Indies", "South Africa", "Sri Lanka"};
  8.   for(String s : semiFinals) {
  9.    br.write(s);
  10.    br.write(System.getProperty("line.separator"));
  11.   }
  12.   br.close();
  13.  }
  14.  catch(IOException iO) {
  15.   System.out.println("The file could not be created/opened/closed");
  16.  }
  17. }
  18.  
  19.  

Notice the use of System.getProperty("line.separator"); to write a return
This method of opening a file overrides the data that was on the file.
To open the file in append mode, simply use
Expand|Select|Wrap|Line Numbers
  1. br = new BufferedWriter(new FileWriter(fileName, true));
  2.  
These approaches should not be used for manipulating .doc, pdf, xls e.t.c Instead one should use more specific packages
Mar 27 '07 #1
19 16835
JosAH
11,448 Expert 8TB
I don't want to exhibit myself as a nitpicker but why don't you just simply use
a BufferedReader for this instead of a Scanner. BufferedReaders are available
in Java 1.4 and before while those Scanners are only available starting from
Java 1.5 and up. BufferedReaders are much simpler too.

kind regards,

Jos (<--- nitpicker ;-)
Mar 29 '07 #2
r035198x
13,262 8TB
I don't want to exhibit myself as a nitpicker but why don't you just simply use
a BufferedReader for this instead of a Scanner. BufferedReaders are available
in Java 1.4 and before while those Scanners are only available starting from
Java 1.5 and up. BufferedReaders are much simpler too.

kind regards,

Jos (<--- nitpicker ;-)

And for those who prefer the nitpicker's advice

Expand|Select|Wrap|Line Numbers
  1.  
  2. import java.io.*;
  3. class FileTest1 {
  4. public static void main(String args[]) {
  5. BufferedReader inputFile = null;
  6. try {
  7. inputFile = new BufferedReader (new FileReader("FileTest1.java"));
  8. while((String line = inputFile.readLine()) != null) {
  9.          System.out.println(line);
  10. }
  11.  
  12. }
  13. catch(FileNotFoundException fNFE) {
  14. System.out.println("The file was not found");
  15. }
  16. catch(IOException iO) {
  17.     System.out.println("IO error");
  18. }
  19. finally {
  20. inputFile.close();
  21. }
  22.  
  23.  
  24. }
  25.  
  26.  
Mar 29 '07 #3
JosAH
11,448 Expert 8TB
And for those who prefer the nitpicker's advice
:-)

kind regards,

Jos

ps. while I'm at it, other IOExceptions can be thrown too you know ;-)
Mar 29 '07 #4
r035198x
13,262 8TB
:-)

kind regards,

Jos

ps. while I'm at it, other IOExceptions can be thrown too you know ;-)
But of course Jos.

At which point I will now have to edit the post.
Mar 29 '07 #5
JosAH
11,448 Expert 8TB
But of course Jos.

At which point I will now have to edit the post.
I'm sorry for stirring this all up; I'm a nasty nitpicker ;-)

kind regards,

Jos
Mar 29 '07 #6
hello every body

I need a help please help me if you can
what functions can we use to send multimedia (vedio,oudio,imeges) using java through socket .


send any thing about this subject to my e-mail : <email removed:Against site rules>
thanks ................
Mar 31 '07 #7
JosAH
11,448 Expert 8TB
hello every body

I need a help please help me if you can
what functions can we use to send multimedia (vedio,oudio,imeges) using java through socket .


send any thing about this subject to my e-mail : dreams294@hotmail.com
thanks ................
Please start you own topic for your question; don't pollute anyone else's topic.

kind regards,

Jos
Mar 31 '07 #8
I don't want to exhibit myself as a nitpicker but why don't you just simply use
a BufferedReader for this instead of a Scanner.
Can't the Scanner class be a better option if, for instance, someone wanted to easily extract various forms of data from the input say one structured with integers floats and strings all on the same line? Of course you CAN use the BufferedReader, but the scanner may be a better choice for an actual solution to a problem.

Just my 2c.
Apr 18 '07 #9
JosAH
11,448 Expert 8TB
Can't the Scanner class be a better option if, for instance, someone wanted to easily extract various forms of data from the input say one structured with integers floats and strings all on the same line? Of course you CAN use the BufferedReader, but the scanner may be a better choice for an actual solution to a problem.

Just my 2c.
Sure, a Scanner would be much better for that purpose, but for the purpose
shown in the article a Scanner would be overkill; that's why I was nitpicking ;-)
(and besides that, Scanners are only here with us, starting at Java 1.5)

kind regards,

Jos
Apr 18 '07 #10
jyohere
73
Sure, a Scanner would be much better for that purpose, but for the purpose
shown in the article a Scanner would be overkill; that's why I was nitpicking ;-)
(and besides that, Scanners are only here with us, starting at Java 1.5)

kind regards,

Jos
I want to read on a field by field basis say

Name Age DateOfBirth

Jyo 25 28-11-82
Ram 30 20-12-81



say I want to read the above file and find out the entries whose DOB is between two given dates
May 8 '07 #11
JosAH
11,448 Expert 8TB
I want to read on a field by field basis say

Name Age DateOfBirth

Jyo 25 28-11-82
Ram 30 20-12-81



say I want to read the above file and find out the entries whose DOB is between two given dates
Read the API docs for the Scanner class and use the code supplied
in this tip of the week to read all non-white space tokens. Oh, before I forget,
the FileReader or FileInputStream classes top it all off.

kind regards,

Jos
May 8 '07 #12
nomad
664 Expert 512MB
Hey a great posting would be how to use a Arraylist.
code to build arraylist
code to create output file and write arraylist
code to read input files and rebuild an Arraylist
code to display the contents on an arraylist.

This was a hard one for me to understand, and sometimes it still is.

nomad.
just my two cents.
May 8 '07 #13
JosAH
11,448 Expert 8TB
Hey a great posting would be how to use a Arraylist.
code to build arraylist
code to create output file and write arraylist
code to read input files and rebuild an Arraylist
code to display the contents on an arraylist.

This was a hard one for me to understand, and sometimes it still is.
Why don't you try it yourself? You try to write a nice concise article; post your
attempts in this forum and I for one will help you out when you're stuck. When
the article is finished you can stick it in the Articles section. deal?

kind regards,

Jos
May 8 '07 #14
nomad
664 Expert 512MB
Why don't you try it yourself? You try to write a nice concise article; post your
attempts in this forum and I for one will help you out when you're stuck. When
the article is finished you can stick it in the Articles section. deal?

kind regards,

Jos
How did I get invloved with this. Heck I'm just starting out in Java. I have only done a several projects. Two with Arraylist and I had a very very hard time doing those....I don't even know if I did those right, because the instructor has not grade them.
Besides I think the viewer would rather see ane Expert like you do it Jos.

nomad.
Maybe in a few months when I get more under my belt. I would do one for Flash or HTML...
May 8 '07 #15
JosAH
11,448 Expert 8TB
How did I get invloved with this. Heck I'm just starting out in Java. I have only done a several projects. Two with Arraylist and I had a very very hard time doing those....I don't even know if I did those right, because the instructor has not grade them.
Besides I think the viewer would rather see ane Expert like you do it Jos.
Stage fright? ;-) I promised I'd help you out and maybe during the 'making' of
the article others will join us in this forum. It could be fun. I promise I won't
'attack' you ;-) Why not give it a try? All we have to come up with now is a
nice, simple problem/project that naturally has to do with Lists.

kind regards,

Jos
May 8 '07 #16
nomad
664 Expert 512MB
Stage fright? ;-) I promised I'd help you out and maybe during the 'making' of
the article others will join us in this forum. It could be fun. I promise I won't
'attack' you ;-) Why not give it a try? All we have to come up with now is a
nice, simple problem/project that naturally has to do with Lists.

kind regards,

Jos
OK Jos...
I making a arraylist program for you It might be too long but it is one of my assignments. I could shorten it.
Anyways here is the code so far, but I'm having problem

I can not invoke the findPerson method. It should work because I have done this in the past.
I did a debug and got this error.

<terminated>EmployeeData (1) [Java Application]
<disconnected>arrayproject.EmployeeData at localhost:1253
<terminated, exit value: 0>C:\Program Files\EasyEclipse Desktop Java 1.2.1\jre\bin\javaw.exe (May 9, 2007 2:04:22 PM)

I have attached my whole project and if someone can help me that would be great..


Expand|Select|Wrap|Line Numbers
  1. class PersonClass {
  2.     private String empid;
  3.     private String lname;
  4.     private String fname;
  5.     private String street;
  6.     private String city;
  7.     private String state;
  8.     private String zip;
  9.     private double payrate;
  10.     private int yearsworked;
  11.     public PersonClass(String id) {
  12.         empid = id;
  13.     }
  14.     public PersonClass(String id, String ln, String fn, String st, String ct, String se, String zp, double pr, int yw) {
  15.         empid = id;
  16.         lname = ln;
  17.         fname = fn;
  18.         street = st;
  19.         city = ct;
  20.         state = se;
  21.         zip = zp;
  22.         payrate = pr;
  23.         yearsworked = yw;
  24.  
  25.     }
  26.  
  27.     // accessors
  28.     public String getID() {return empid;}
  29.  
  30.     public String getFname() {return fname;}
  31.  
  32.     public String getLname() {return lname;}
  33.  
  34.     public String getStree() {return street;}
  35.  
  36.  
  37.     public String getCity() {return city;}
  38.  
  39.     public String getState() {return state;}
  40.  
  41.     public String getZip() {return zip;}
  42.  
  43.     public double getPayrate() {return payrate;}
  44.  
  45.     public int getYearsworked() {return yearsworked;}
  46.  
  47.  
  48. }
  49.  
  50.  
  51. public class EmployeeData {
  52.     static ArrayList<PersonClass> arlist;
  53.     static Scanner kbd;
  54.  
  55.     public static PersonClass makePerson() {
  56.         PersonClass temp = null;
  57.  
  58.         // prompt for data
  59.         String id;
  60.         String ln;
  61.         String fn;
  62.         String st;
  63.         String se;
  64.         String ct;
  65.         String zp;
  66.         double pr;
  67.         int years;
  68.  
  69.         System.out.print("Enter ID Number ==>");
  70.         id = kbd.next();
  71.  
  72.         System.out.print("Enter Last Name ==>");
  73.         ln = kbd.next();
  74.  
  75.         System.out.print("Enter First Name ==>");
  76.         fn = kbd.next();
  77.  
  78.         System.out.print("Enter the address==>");
  79.         st = kbd.next();
  80.  
  81.         System.out.print("Enter City ==>");
  82.         ct = kbd.next();
  83.  
  84.         System.out.print("Enter State ==>");
  85.         se = kbd.next();
  86.  
  87.         System.out.print("Enter Zip ==>");
  88.         zp = kbd.next();
  89.  
  90.         System.out.print("Enter payrate as double ==>");
  91.         pr = kbd.nextDouble();
  92.  
  93.         System.out.print("Enter years worked ==>");
  94.         years = kbd.nextInt();
  95.  
  96.         // make an object
  97.         temp = new PersonClass(id, ln,fn,st,ct,se, zp, pr,years);
  98.  
  99.         return temp;
  100.     }
  101.  
  102.     public void displayMatch() {
  103.  
  104.     String id_flag = "";
  105.     Scanner kbd = new Scanner(System.in);
  106.     System.out.println("Enter your info please ie: AB1234: ");
  107.     id_flag = kbd.next();
  108.     boolean notfound = true;
  109.     for (PersonClass e : arlist) {
  110.         String emp = e.getID();
  111.         if (emp.equals(id_flag)) {
  112.             System.out.println("Hello" + ("e.lname"));
  113.             notfound = false;
  114.         }
  115.     }
  116.     if (notfound == true) {
  117.         System.out.println("Error - Employee not found");
  118.         // back to menu?
  119. }
  120.  
  121.     }//close findperson
  122.  
  123.     public static void main(String[] args) {
  124.         EmployeeData emp = new EmployeeData();
  125.         // make array list object
  126.         arlist = new ArrayList<PersonClass>();
  127.  
  128.         // make a scanner
  129.         kbd = new Scanner(System.in);
  130.  
  131.         int choice;
  132.         System.out.println("Make a Section: ");
  133.         System.out.println("1. Enter Employees ");
  134.         System.out.println("2. Find Employees ");
  135.         System.out.println("3. Exit this Program ");
  136.         System.out.print("\nPlease press Enter afer each response");
  137.         System.out.println("Enter your chose please: ");
  138.         choice = kbd.nextInt();
  139.         kbd.nextLine();
  140.         if (choice == 1) { // if 1 is select go to makePerson
  141.  
  142.         // create people until select stop
  143.         boolean endData = false;
  144.  
  145.         while (!endData) {
  146.             PersonClass temp = makePerson();
  147.             arlist.add(temp);
  148.             System.out.println("Add More employees (Y/N)-->");
  149.  
  150.             String ans = kbd.next();
  151.  
  152.             if (ans.equalsIgnoreCase("N")) {
  153.                 endData = true;
  154.             }
  155.         }//close while loop
  156.         if (choice == 2) { // if 2 is select go to find
  157.             emp.displayMatch();
  158.  
  159.  
  160.         }// close the choice==2
  161.         if (choice == 3) {
  162.             System.out.printf("Good bye");
  163.         }// close the choice == 3
  164.  
  165.  
  166.         // print out all elements of array list
  167.         for (PersonClass idx : arlist) {
  168.             System.out.printf("Employee Id is %n", idx.getID());
  169.                 System.out.printf("Name is %s - %s%n", idx.getFname(),idx.getLname());
  170.                 System.out.printf("Street is %s%n", idx.getStree());
  171.                 System.out.printf("City is %s%n", idx.getCity());
  172.                 System.out.printf("State is %s%n", idx.getState());
  173.                 System.out.printf("Zip Code is %s%n", idx.getZip());
  174.                 System.out.printf("Payrate is %8.2f%n", idx.getPayrate());
  175.                 System.out.printf("Years worked are %d\n", idx.getYearsworked());
  176.                 System.out.println("--------------------");
  177.         }
  178.     }
  179. }
  180. }


Thanks a bunch
nomad
May 9 '07 #17
JosAH
11,448 Expert 8TB
I created a new thread for Nomad's Article under construction so there'll be no
need anymore to hijack this thread.

kind regards,

Jos
May 10 '07 #18
The program below simply reads a file called FileTest1.java(itself) and prints it to the console

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. import java.util.Scanner;
  4. import java.io.*;
  5. class FileTest1 {
  6.  public static void main(String args[]) {
  7.   Scanner inputFile = null;
  8.   try {
  9.    inputFile = new Scanner(new File("FileTest1.java"));
  10.    while(inputFile.hasNext()) {
  11.     System.out.println(inputFile.next());
  12.    }
  13.  
  14.   }
  15.   catch(FileNotFoundException fNFE) {
  16.    System.out.println("The file was not found");
  17.   }
  18.   finally {
  19.    inputFile.close();
  20.   }
  21.  
  22.  } 
  23.  
  24. }
  25.  
  26.  
  27.  
Two methods of the Scanner class were used here hasNext and next.
You should be able to see what these methods are doing here if not then you can check with the Scanner page on sun's Java API.
This is the recommended way of reading a file these days.

To write to a file, use the FileWriter class wrapped in a BufferedWriter

Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. public static void writeFile(String fileName) {
  4.  BufferedWriter br = null;
  5.  try {
  6.   br = new BufferedWriter(new FileWriter(fileName));
  7.   String[] semiFinals = {"Australia", "West Indies", "South Africa", "Sri Lanka"};
  8.   for(String s : semiFinals) {
  9.    br.write(s);
  10.    br.write(System.getProperty("line.separator"));
  11.   }
  12.   br.close();
  13.  }
  14.  catch(IOException iO) {
  15.   System.out.println("The file could not be created/opened/closed");
  16.  }
  17. }
  18.  
  19.  

Notice the use of System.getProperty("line.separator"); to write a return
This method of opening a file overrides the data that was on the file.
To open the file in append mode, simply use
Expand|Select|Wrap|Line Numbers
  1. br = new BufferedWriter(new FileWriter(fileName, true));
  2.  
These approaches should not be used for manipulating .doc, pdf, xls e.t.c Instead one should use more specific packages
how to apply in JFileChooser?..that it can read the file that was selected.
Sep 27 '07 #19
chaarmann
785 Expert 512MB
Usually loading a whole file at once is faster than looping through it line by line. Especially if the file resides on a network device.

Here is the code:
Expand|Select|Wrap|Line Numbers
  1. // check existence
  2. File file = new File(sourceFileName);
  3. if (! file.exists()) throw new IOException("ERROR: no such source file: " + sourceFileName);
  4.  
  5. // read as string
  6. FileInputStream fileInputStream = new FileInputStream(sourceFileName);
  7. byte data[] = new byte[fileInputStream.available()];
  8. fileInputStream.read(data);
  9. String content = new String(data);
  10.  
  11. // do whatever you want with the result
  12. System.out.println("File contains:" + content);
Oct 30 '08 #20

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

Similar topics

2
by: dunnm | last post by:
This is probably a more appropriate location to post this question. I should have know that since I've found most of the other PHP/PDF information contained in this group. Here's my issue...I...
5
by: Benjamin de Waal | last post by:
Hey all, I'm trying to figure out how to directly write to a device in Windows. Basically, what I'm wanting to do is create an image of a device (specifically, a CompactFlash card that uses a...
2
by: John Salerno | last post by:
I wrote this code just to experiment with writing to and reading from a file. It seems to work fine when writing, but when reading the file, it only prints the filepath to the screen, not the file...
2
by: Robert Reijntjes | last post by:
Hi, I need to read/write data from/to binary files that have an already defined. This means I can't define classes with the attribute. The files also have arrays with variable length. This...
8
by: smeenehan | last post by:
This is a bit of a peculiar problem. First off, this relates to Python Challenge #12, so if you are attempting those and have yet to finish #12, as there are potential spoilers here. I have five...
6
by: arne.muller | last post by:
Hello, I've come across some problems reading strucutres from binary files. Basically I've some strutures typedef struct { int i; double x; int n; double *mz;
10
by: Tyler | last post by:
Hello All: After trying to find an open source alternative to Matlab (or IDL), I am currently getting acquainted with Python and, in particular SciPy, NumPy, and Matplotlib. While I await the...
7
by: random guy | last post by:
Hi, I'm writing a program which creates an index of text files. For each file it processes, the program records the start and end positions (as returned by tellg()) of sections of interest,...
2
by: Clive Green | last post by:
Hello peeps, I am using PHP 5.2.2 together with MP3_Id (a PEAR module for reading and writing MP3 tags). I have been using PHP on the command line (Mac OS X Unix shell, to be precise), and am...
0
Guido Geurs
by: Guido Geurs | last post by:
I'm writing a program that list the contents of a CDrom and also the contents of the ZIP files. When there is a bad Zip file on the CD, the program keeps traying to reed the file and after +- 50...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 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 former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.