• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

how to read from a file ?

 
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.....
 
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();
}
}
 
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);
}
}
}
 
Get out of my mind! Look! A tiny ad!
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic