Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to read from a file ?

 
mark stone
Ranch Hand
Posts: 417
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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);
}
}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic