GeeCON Prague 2014*
The moose likes I/O and Streams and the fly likes how to read from a file ? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » I/O and Streams
Bookmark "how to read from a file ?" Watch "how to read from a file ?" New topic
Author

how to read from a file ?

mark stone
Ranch Hand

Joined: Dec 18, 2001
Posts: 417
i need to perform some string operations on strings contained inside a text file. So how does one read the strings from the text file into the program ?
eg say the text file contains names:
john mary edwin bill george rossane
i need to be able to read each of the above strings into my program and do say things with methods like startsWith(), endsWith() etc.
how do we read in the strings sequentially one after one.....
Steve O Thomas
Greenhorn

Joined: Jul 18, 2002
Posts: 2
Had a few problems with this myself.
This seems to work ok for me though.
import java.io.*;
public class rw_line
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("old.txt");//Open the files
File outputFile = new File("new.txt");
BufferedReader in = new BufferedReader(new FileReader(inputFile));
PrintStream out = new PrintStream(new FileOutputStream(outputFile));

String str;
while ((str = in.readLine()) != null)//While the end of the file has not been reached
{
out.println(str); //Print the line into the file
}
in.close();//Close the files
out.close();
}
}
Sandhya Chamala
Greenhorn

Joined: Aug 06, 2002
Posts: 4
Hi,
Check whether the code below solves ur problem.
code is:
--------
import java.io.*;
import java.util.*;
public class rw_line
{
public static void main(String[] args) throws IOException
{
File inputFile = new File("Old.txt");
BufferedReader in = new BufferedReader(new FileReader(inputFile));
String str = null, str1 = "";

while ((str = in.readLine()) != null)
{
str1 += str+" ";
}

in.close();

StringTokenizer tokenizer = new StringTokenizer(str1," ");

String token = null;

while (tokenizer.hasMoreTokens())
{
token = tokenizer.nextToken();

System.out.println("Each name is :"+token);
}
}
}
 
GeeCON Prague 2014
 
subject: how to read from a file ?