reading username and password from file in java - java

I'm making some really simple program in java just to see how I/O works, but I have a problem. I've created"test.txt" file, and now I'm trying to (over Scanner) enter username and password every time when I start program, which is not big deal. I made my program read content from file and write to console. But, my problem is, I want that every time I run program and enter new username that my program go through the file, read every username and give me a warning if username already exist.

Not sure if this is what you're looking for but this should do the job. It's a quick simple solution.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String filePath = "{YOUR_FILEPATH_TO_TEST.TXT}";
Scanner scanner = new Scanner(System.in);
System.out.println("Enter your username: ");
String username = scanner.nextLine();
System.out.println("Checking to see if username exists...");
BufferedReader bufferedReader;
try {
bufferedReader = new BufferedReader(new FileReader(filePath));
String line;
boolean usernameExists = false;
while((line = bufferedReader.readLine()) != null) {
if (line.equals(username)) {
usernameExists = true;
break;
}
}
if (usernameExists) {
System.out.println("Username exists! Please try again.");
} else {
System.out.println("Username accepted");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}

Related

How to read .evtx extension file through java program

I don't know if it is possible or not, but my requirement is like - I have to read data from a file called System.evtx in my java program.
While I am doing this like simple file reading I am getting some ASCII character or I can say un-readable format.
Is there any way to solve this issues.
Thanks in advance.
This is a difficult question to answer without an example of the file content, but after some googling it seems to be a windows event log file? So im unsure about the exact format but apparently they can be converted to .csv files using powershell:
Get-WinEvent -Path c:\path\to\eventlog.evtx |Export-Csv eventlog.csv
Once its in a csv format you could simple parse them in the traditional way of csv or just split by comma's etc.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class CSVReader {
public static void main(String[] args) {
String csvFile = "eventlog.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] line = line.split(cvsSplitBy);
for(int i=0;i<line.length;i++){
System.out.println(line[i]);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

My program doesn't open a text file to read it

course.txt file is not read by my code. It allows me to enter the file name, but doesn't open the file.
package javaexam;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.io.BufferedReader;
import java.util.Scanner;
public class BufferReader {
public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
BufferedReader bf = null; // shows warning that assigned but never used
String line;
System.out.println("Please enter the file name");
try {
bf = new BufferedReader(new FileReader("C:\\Users\\MohammedArfa\\Desktop\\New folder\\" + scanner.next()));
} catch(FileNotFoundException fnfex) {
//shows warning that the buffer assignment is declared but never used
System.out.println(fnfex.getMessage()+"The file was not found");
}
System.exit(0);
try {
while((line=bf.readLine()) != null) {
System.out.println(line);
}
} catch(IOException ex) {
System.out.println(ex.getMessage()+"Error reading file");
} finally {
System.out.println(0);
}
}
}
Move the system.exit(0) into the catch statement above...
try {
bf = new BufferedReader(new FileReader("C:\\Users\\MohammedArfa\\Desktop\\New folder\\" + scanner.next()));
} catch(FileNotFoundException fnfex) {
//shows warning that the buffer assignment is declared but never used
System.out.println(fnfex.getMessage()+"The file was not found");
System.exit(0);
}
If the system.exit(0) is not inside the catch then it is always being executed which terminates your program before you reach the print out loop.

Issue with switch statement in java

i currently have this code
My problem is that when i give a number 1 or 2, it doesn't give it and just says 'Not valid input'.
It would be nice if anyone could explain me why is it happening.
Thanks for any answer.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
public class Screen {
private static BufferedReader stdin;
private static PrintStream os;
public static void main(String[] args) throws IOException{
try {
stdin = new BufferedReader(new InputStreamReader(System.in));
} catch (Exception e) {
System.exit(1);
}
try {
switch (Integer.parseInt(selectAction())) {
case 1:
os.println("1");
System.err.print("Hello World ");
break;
case 2:
os.println("2");
System.err.print("Another Word ");
break;
}
} catch (Exception e) {
System.err.println("not valid input");
}
}
public static String selectAction() throws IOException {
System.out.println("1. Hello World.");
System.out.println("2. Another Word.");
System.out.print("\nMake selection: ");
return stdin.readLine();
}
}
Provide an initialization for os to prevent the NullPointerException. Your code works if I change the os declaration like
private static PrintStream os = System.out;
Also, please don't swallow the Exception
} catch (Exception e) {
System.err.println("not valid input: " + e.getMessage());
e.printStackTrace(System.err);
}

Deleting a line that starts with a particular number in a text file

I've been trying to come up with a class that deletes a line from a text file that starts with a particular number.
What I currently have doesn't show any code errors and also runs without erros; shows "BUILD SUCCESSFUL" on netbeans, but doesn't do anything to the line, or any part of the textfile whatsoever, let alone delete the intended line.
Could anyone please look at my code and please advise me on what I might have done wrong, or is missing?
Thanks a lot in advance.
Heres my code:
package Database;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
public class Edit {
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File("/D:/TestFile.txt/");
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(line.startsWith(lineToRemove))) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
Edit edit = new Edit();
edit.removeLineFromFile("/D:/TestFile.txt/", "2013001");
}
}
There is a problem with your logic ... you are saying if the line equals to itself that starts with something which will never happen unless the line only consist of the line you want to remove
if (!line.trim().equals(line.startsWith(lineToRemove))
i think needs to be just
if (!line.startsWith(lineToRemove))
Change the if condition to:
if (!line.startsWith(lineToRemove)) {
pw.println(line);
pw.flush();
}

Java text file reading program with bufferedreader and FileReader. Compiling But not working

This program is compiling though not working. It just handling the opening file exception. Please help me.Thanks for your time.
import java.io.*;
import java.util.Scanner;
public class ReadingFile {
/**
* #param args
*/
public static void main(String[] args) {
ReadingFile rf = new ReadingFile();
rf.printOnScr();
}
private BufferedReader openFile(String meString){
Scanner sc = new Scanner(System.in);
BufferedReader bf = null;
while (bf == null) {
try {
System.out.println("Enter a file name");
String fileName = sc.nextLine();
FileReader b = new FileReader(fileName);
bf = new BufferedReader(b);
} catch (IOException e) {
System.out.println("The file you are trying to open dose not exist.");
}
}
return bf;
}
private void printOnScr() {
BufferedReader br = openFile("Please enter a file");
try {
while(true){
String line = br.readLine();
if(line == null) break;
System.out.println(line);
}
br.close();
} catch (IOException e) {
System.out.println("The line you are trying to access have problem/s");
}
}
}
Very probably you're not specifying the correct path to the file when you type it. It should either be an absolute path or a relative path based at your current working directory. To see exactly what's happening, though, you'll need to look at the exception that's thrown. Either print it out with
e.printStackTrace()
or wrap it in an unchecked exception:
throw new IllegalStateException(e);
or let IOException be thrown from openFile(), through printOnScr(), and out of main()

Categories