Find all string “ID” in a .txt file [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
How do I find all string "ID" in an existed .txt file and get how many strings were found?
I have a .txt file like:
Product ID = "001", Product Name = "P1"
Product ID = "002", Product Name = "P2"
Product ID = "003", Product Name = "P3"
...
I would like to add Product ID = "LASTEST_ID_PLUS_1, Product Name = "new" at the end of file, but don't know how to get the last ID number.

String filename = "test.txt";
int numOfIds = 0;
try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line = null;
while ((line = br.readLine()) != null) {
if (line.contains("Product ID = ")) {
numOfIds++;
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Should be a good starting point. Save up the last read ID and then use that for appending.
Edit:
After looking at your question again, I'm not even sure why your .txt file has Product ID =in it. Make the txt file look like this for much easier handling:
001,P1
002,P2
003,P3
unless you didn't show the entire file and there are different things than product IDs stored.

InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
while(CurLine = in.readLine())
//after exiting the loop
you can use StringBuilder methods "indexOf" and "subString".
then you can catch the last id.

LineNumberReader lnr = null;
try {
File file = new File("productList.txt");
lnr = new LineNumberReader(new FileReader(file));
lnr.skip(Long.MAX_VALUE);
int lineNumber = lnr.getLineNumber();
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(file, true)));
String productName = getProductName(); // may be a user input
out.println("Product ID = \""+lineNumber+"\", Product Name = \""+productName+"\"\n");
out.close();
} catch (Exception ex) {
// handle it
} finally {
try {
lnr.close();
} catch (IOException ex) {
Logger.getLogger(H.class.getName()).log(Level.SEVERE, null, ex);
}
}
I've assumed each line contains a product and sequence number start with 1.

Related

Out of bounds error, while reading file then splitting it [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I've been getting an Array Index Out of Bounds Error.
Basically I have a file where a user name and password is saved lke this: user:password
I'm trying to read the file to check if a new user is already signed in or not. This is in a thread and also using a socket.
private void authentication(String user, String password) {
List<String> nomes = new ArrayList<>();
List<String> pass = new ArrayList<>();
BufferedReader reader;
try {
FileWriter fw = new FileWriter("users.txt", true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw);
BufferedReader br = new BufferedReader(new FileReader("users.txt"));
//String line;
String line;
while((line = br.readLine())!=null){
String[] pair = line.split(";");
nomes.add(pair[0]);
pass.add(pair[1]);
}
/*while ((line = br.readLine()) != null) {
String[] info = line.split(":");
System.out.println(line);
System.out.println(info[0]);
System.out.println(info[1]);
}*/
if(nomes.isEmpty()) {
out.println(user + ":" + password);
System.out.println("Novo Utilizador Autenticado.");
System.out.println("Bem Vindo!!");
}else if(nomes.contains(user)) {
bw.newLine();
if(password.equals(pass.get(nomes.indexOf(user)))) {
System.out.println("Utilizador autenticado com sucesso!");
System.out.println("Bem Vindo de Volta!!");
}
}else {
terminate();
}
bw.close();
br.close();
out.close();
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
The error is happening in the last line on the pair[1]. It has a value but for some reason isn't seeing it.
Your text in the file is like "user:password" and you are trying to split it with ";". So pair[1] won't have any value. You should try split it with ":"
Try to access the values dynamically using index instead of hardcoded 0,1 to avoid index out of bond exception :
while ((line = br.readLine()) != null) {
String[] info = line.split(":");
int index = 0;
System.out.println(line);
while(index < info.length){
System.out.println(info[index++]);
}
}

displaying data from .txt file [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
need help, i want to display the name of the person who just logged in, here is my login code
public void Masuk(){
try {
String lokasi = "D:/settings.txt";
String username = txtUser.getText();
String password = txtPass.getText();
FileReader fr = new FileReader(lokasi);
BufferedReader br = new BufferedReader(fr);
String line, user, pass;
boolean isLoginSuccess = false;
while ((line = br.readLine()) != null) {
user = line.split(" ")[1].toLowerCase();
pass = line.split(" ")[2].toLowerCase();
if (user.equals(username) && pass.equals(password)) {
isLoginSuccess = true;
this.dispose();
new Main_Menu(this, rootPaneCheckingEnabled).show();
break;
}
}
if (!isLoginSuccess) {
JOptionPane.showMessageDialog(null, "USERNAME/PASSWORD WRONG", "WARNING!!", JOptionPane.WARNING_MESSAGE);
}
fr.close();
}catch(Exception e){
e.printStackTrace();
}
}
the login is in form, i used JDialog to dipslay the name of the person who just logged in(MainMenu), here is my MainMenu code right now
public void Berhasil(){
String data = "D:/Settings.txt";
try {
FileReader fr = new FileReader(data);
BufferedReader br = new BufferedReader(fr);
String line = br.readLine(),nama;
nama = line.split(" ")[0].toLowerCase();
String message = "Selamat datang "+ nama;
String text;
while ((line = br.readLine()) != null)
txtBerhasil.setText(""+message);
}
catch (FileNotFoundException fnfe) {
fnfe.getMessage();
}
catch (IOException ioe) {
ioe.getMessage();
}
}
the .txt file looks like this
Name Username Password
i only want to write the name of the person who just logged in
I'm assuming you want to read some text (the user's information) from a text file. There are several ways to do it. This is one way:
File file = new File("path/to/file.txt");
Scanner sc = new Scanner(file);
String thisLine = null;
while (sc.hasNextLine()){
thisLine = sc.nextLine();
}
Now you can do whatever you want with thisLine. Say you want the first word in the first line:
String[] words = thisLine.split(" ");
System.out.println(words[0]);
This would print the first word in the first line of your txt file. I used space as the separator but it actually depends on what separator you used in yout txt file when you were saving the info. For instance, you may want to use "\t" if tab was used as the separator.

why doesn't my file delete no matter why I do? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
public void removeLine(String s) throws IOException, FileNotFoundException{
File tempFile = new File("temp.txt");
FileInputStream reader = new FileInputStream(sharkFile);
Scanner scanner = new Scanner(reader);
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile, true));
String currentLine;
while(scanner.hasNextLine()){
currentLine = scanner.nextLine();
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
trimmedLine.equals(sharkName);
if(trimmedLine.equals(sharkName)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
scanner.close();
scanner = null;
reader.close();
writer.flush();
writer.close();
writer = null;
System.gc();
if(!sharkFile.delete()){
System.out.println("Could not delete file d");
return;
}
if(!tempFile.renameTo(sharkFile)){
System.out.println("Could not rename file");
return;
}
}
I've gone through numerous threads on stackoverflow and have implemented those changes but my file just won't delete. Appreciate the help.
The File API is notoriously weak on explaining why something fail, e.g. File.delete() simply returns a boolean, and value false cannot explain why.
Use the new Path API instead.
Also, please (PLEASE!) use try-with-resources.
Scanner is slow, so better to use BufferedReader, and for writing the lines back with newlines, use a PrintWriter.
Path sharkPath = sharkFile.toPath();
Path tempPath = Paths.get("temp.txt");
Charset cs = Charset.defaultCharset();
try (BufferedReader reader = Files.newBufferedReader(sharkPath, cs);
PrintWriter writer = new PrintWriter(Files.newBufferedWriter(tempPath, cs, StandardOpenOption.CREATE, StandardOpenOption.APPEND, StandardOpenOption.WRITE)))) {
for (String currentLine; (currentLine = reader.readLine()) != null; ) {
String trimmedLine = currentLine.trim();
System.out.println(trimmedLine);
if (! trimmedLine.equals(sharkName))
writer.println(currentLine);
}
}
Files.delete(sharkPath); // throws descriptive exception if cannot delete
Files.move(tempPath, sharkPath); // throws exception if cannot move
Use below code, rename file before delete, it's appearing that you are accessing file name after delete:
try { //rename file first
tempFile.renameTo(sharkFile);
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Unable to rename.");
}
try {
sharkFile.delete();
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, "Unable to delete.");
}

how to extract ipaddress,date&time,http:// in a log file using java [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
if my logfile contains various lines like
sample data:/* 10.1.5.121 - d31f [17/Sep/2014:07:00:04 +0530] "POST http://webres3.qheal.ctmail.com/SpamResolverNG/SpamResolverNG.dll?DoNewRequest HTTP/1.0" 200 164 "HTTP" ""/*
how to extract ipaddress,date&time,http://... alone using Stringtokenizer concept.
File file = new File("test.txt");
String word = "abc,catch,profile";
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch (FileNotFoundException e) {
System.out.println("Error " + e);
}
// now read the file line by line
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
StringTokenizer st = new StringTokenizer(word, ",");
while (st.hasMoreTokens()) {
if (line.contains(st.nextToken())) {
System.out.println(line);
break;
}
}
}
scanner.close();`
I have made some modifications in the previous Code of mine.. Hope this will work for You..
File file = new File("FileTest.txt");
String[] findMe = {"abc","profile","catch"};
Scanner scanner = null;
try {
scanner = new Scanner(file);
} catch(FileNotFoundException e) {
e.printStackTrace();
}
int i=1;
ArrayList<String> neededLines = new ArrayList<String>();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
for (String string : findMe) {
if(line.contains(string)){
if(!neededLines.contains(line))
neededLines.add(line);
}
}
}
System.out.println(neededLines);

How to replace the star {*} in text file with a number [duplicate]

This question already has answers here:
replace String with another in java
(7 answers)
Closed 3 years ago.
My contents of text file looks something like this
Synonyms of Fluster:
*panic
*perturb
*disconcert
*confuse
......
Now i wish to replace the * with numbers.Something like this.
output
Synonyms of Fluster:
1)panic
2)perturb
3)disconcert
4)confuse
......
Edit:
Integer count = 1;
File input = new File("C:\\Sample.txt");
File output = new File("C:\\output.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(input)));
Writer writer =new FileWriter(output);
while((line=reader.readLine())!=null)
{
if(line.contains("*"))
{
line.replace("*",count.toString() );
writer.write(line);
count++;
}
else
{
writer.write(line);
}
}
This is what i had tried before posting question here..But this doesn't seem to work.
Now can somebody help me out..?
You should write a JAVA program.
Here's something that may get you started (rough code):
BufferedReader br = new BufferedReader(new FileReader(file));
//start reading file line-by-line
while ((line = br.readLine()) != null) {
//replace * with whatever you want
// Use a counter to keep track of lines to give corresponding line number
String val = line.replace("*",counterVar.toString());
}
br.close();
Write back to file using BufferedWriter again, wrap it with PrintWriter if you wish to,
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("outputfile")));
Try something like this (Untested code):
try{
List<String> lines = Files.readAllLines(fileName, Charset.defaultCharset());
for (int i = 0; i< lines.size(); i++) {
lines.set(i, lines[i].replace("*", String.valueOf(i)));
}
} catch (IOException e) {
e.printStackTrace();
}
...//Then save the file

Categories

Resources