PDA

View Full Version : reading .txt file


mmcnitt
11-04-2009, 05:15 AM
I'm making a login applet and i can get it to output the information necessary to a file, and i can get it to input all the information from the file for me. However i can't seem to find out how to make it search the file for the information.

I don't wish to show my code, but here's basically the output input method i'm using

import java.io.*;

public class OutputInput
{
// Main method
public static void main (String args[])
{
try
{
// Open an output stream
FileOutputStream fout = new FileOutputStream ("myfile.txt");
String myName = ("Hello World!!!\nLine 2\nLine 3");
// Print a line of text
new PrintStream(fout).println (myName);

// Close our output stream
fout.close();


// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("myfile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}
//Catch exception if any
catch (Exception e)
{
System.err.println("Error: " + e.getMessage());
}
}
}

so if i wanted it to just look and see if the file said "Line 3"?

mmcnitt
11-04-2009, 04:16 PM
well i ended up making a work around where it just makes a seperate file for each login, but if anyone has any ideas for how i can so it in one file that'd be great

ckeyrouz
11-04-2009, 04:38 PM
inside this loop add the following search commands:
while ((strLine = br.readLine()) != null)
{
// Print the content on the console
System.out.println (strLine);
//search for a certain string
if(strLine.indexOf("yourString") != -1)
{
System.out.println("String found");
}
else
{
System.out.println("String not found");
}
}

mmcnitt
11-07-2009, 04:09 PM
thanks ckeyrouz but the only problem i have with that is that so long as you don't misspell it, it finds the string.

ex.

password is hello

h -String found
he -String found
leave it blank -String found
t -String not found

cs_student
11-07-2009, 10:36 PM
I think that the Pattern (http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Pattern.html#sum) class would help you better search for the items you want. This way you can determine what is and isn't acceptable as a match.

mmcnitt
11-08-2009, 08:17 PM
i ended up using a Scanner, actually works quite well, thanks for y'alls help ckeyrouz and cs student