reading file StringTokenizer to int - java

I have create the following program and I am little stuck here.
Here is the code:
class ProductNameQuan{
public static void main(String[] args)
{
String fileName = "stockhouse.txt";
StringTokenizer line;
String ProdName;
String quantity;
try {
BufferedReader in = new BufferedReader(new FileReader(fileName));
line = in.readLine();
while (line != null) {
ProdName = line.nextToken();
quantity = line.nextToken();
System.out.println(line);
line = in.readLine();
}
in.close();
} catch (IOException iox)
{
System.out.println("Problem reading " + fileName);
}
}
}
I am trying to find the way to read from the file the first 10 information's through the array (not arraylist)ProdName and the quantity." plus that I stack in the in.readLine(); propably is not compatible with the StringTokenizer.
Now the other problem is that I need the quantity to be an integer instead of string.
The file includes something like that:
Ball 32
tennis 322
fireball 54
..
.
.
.
.
Any ideas?

I would place this in a helper function, maybe called parseString
class ProductNameQuan {
public static void main(String[] args)
{
...
try {
BufferedReader in = ...
line = in.readLine();
while (line != null) {
ProductNameQuan.parseString(line);
}
}
...
}
public static void parseString(String someString)
{
StringTokenizer st = new StringTokenizer(someString);
while (st.hasMoreTokens()) {
String token = line.nextToken();
try {
int quantity = Integer.parseInt(token)
// process number
} catch(NumberFormatException ex) {
// process string token
}
}
}

Related

With a scanner search on ArrayList the content and print the line

I have a text file (.txt) and I'm stuck here.
I user a BufferReader to read all file and save in a ArrayList then put the ArrayList into a String to remove the , [ ]
Now I need to find the word of the scanner ex: (1001) in the ArrayList that the user want, and print the line of this word and the 4 lines after that. After that, edit this 4 lines and save the ArrayList to a file.
Or have something more simple without using ArrayLists?
Thank you.
System.out.println("Digite o ID ou 1 para sair: ");
Scanner sOPFicheiro = new Scanner(System.in);
opFicheiro = sOPFicheiro.nextInt();
if (opFicheiro == 1){
System.out.println("A voltar ao menu anterior...");
Thread.sleep(1000);
editarFicheiro();
} else {
//Envia para um ArrayList o ficheiro Formandos
ArrayList<String> textoFormandos = new ArrayList<String>();
BufferedReader ler = new BufferedReader(new FileReader(FichFormandos));
String linha;
while ((linha = ler.readLine()) != null) {
textoFormandos.add(linha + "\n");
}
ler.close();
//Remove , [ ] do ArrayList para enviar para o ficheiro
String textoFormandos2 = Arrays.toString(textoFormandos.toArray()).replace("[", "").replace("]", "").replace(",", "");
}
File:
Txt File
save the ArrayList to a file
Your code lucks a mean to write data into the file.
Also invoking close() without a try/catch is a bad practice because it'll lead to resource leaks in case of exceptions.
For this task, you don't need a list, after the match with the given id is found you can write these lines to a file.
To execute this code file "test.txt" must reside under the project folder, file "result.txt" will be created automatically.
public static void main(String[] args) {
try {
readFile(Path.of("test.txt"), Path.of("result.txt"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void readFile(Path target, Path result) throws InterruptedException {
Scanner sOPFicheiro = new Scanner(System.in);
int opFicheiro = sOPFicheiro.nextInt();
if (opFicheiro == 1) {
System.out.println("A voltar ao menu anterior...");
Thread.sleep(1000);
editarFicheiro();
} else {
try (BufferedReader ler = new BufferedReader(new FileReader(target.toFile()));
BufferedWriter br = new BufferedWriter(new FileWriter(result.toFile()))) {
boolean matchIsFound = false;
String linha;
while ((linha = ler.readLine()) != null && !matchIsFound) {
if (linha.contains(String.valueOf(opFicheiro))) {
for (int i = 0; i < 5; i++) {
br.write(linha);
if (i != 4) {
br.newLine();
linha = ler.readLine();
}
}
matchIsFound = true;
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
user input - 1001
Initial contents of the "test.txt" file:
ID: 999
Name: ________________
Data of birth: _______
NIF: _________________
Telephone: ___________
Fim ID: 999
ID: 1001
Name: Cesar Rodrige da Silva Guimaraes
Data of birth: 16/03/2003
NIF: 1111111111
Telephone: 931111111111
Fim ID: 1001
Contents of the "result.txt" file after executing the code:
ID: 1001
Name: Cesar Rodrige da Silva Guimaraes
Data of birth: 16/03/2003
NIF: 1111111111
Telephone: 931111111111
UPDATE
public static void main(String[] args) {
try {
updateUserData(Path.of("test.txt"), Path.of("temp.txt"));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void updateUserData(Path original, Path temp) throws InterruptedException {
Scanner scanner = new Scanner(System.in);
int id = scanner.nextInt();
if (id == 1) {
System.out.println("A voltar ao menu anterior...");
Thread.sleep(1000);
editarFicheiro();
return;
}
String userData = readUserData(temp, id);
String originalContentWithReplacement = readAndReplace(original, userData, id);
writeData(original, originalContentWithReplacement);
}
reading user-data for the given id from the temp file
public static String readUserData(Path temp, int id) {
StringBuilder result = new StringBuilder();
try (var reader = new BufferedReader(new FileReader(temp.toFile()))) {
boolean matchIsFound = false;
String line;
while ((line = reader.readLine()) != null && !matchIsFound) {
if (line.contains(String.valueOf(id))) {
for (int i = 0; i < 5; i++, line = reader.readLine()) {
result.append(line).append(System.getProperty("line.separator"));
}
matchIsFound = true;
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString().stripTrailing();
}
reading the whole contents of the original file and replacing the data for the given id
public static String readAndReplace(Path original, String userData, int id) {
StringBuilder result = new StringBuilder();
try (var reader = new BufferedReader(new FileReader(original.toFile()))) {
String line;
while ((line = reader.readLine()) != null) {
if (!line.contains(String.valueOf(id))) {
result.append(line).append(System.getProperty("line.separator"));
continue;
}
result.append(userData).append(System.getProperty("line.separator"));
for (int i = 0; i < 5; i++) {
line = reader.readLine();
}
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString().stripTrailing();
}
replacing the previous data
public static void writeData(Path original, String content) {
try (var writer = new BufferedWriter(new FileWriter(original.toFile()))) {
writer.write(content);
} catch (IOException e) {
e.printStackTrace();
}
}
Instead of using an ArrayList use a StringBuilder :
StringBuilder textoFormandos = new StringBuilder();
while ...
textoFormandos.append(linha + "\n");
...
String textoFormandos2 = textoFormandos.toString();
This way you won't need to remove anything. For the rest you need to clear the requirements.

How to read every line after :

I have a TXT file like this:
Start: Here is a random introduction.
Items:
Item 1
Item 2
Item 3
Item 4
End: Here is a random outro.
I want to retrieve Item 1, Item 2, Item 3, Item 4 and put them into a data structure like a HashMap. How can I achieve this?
Here is what I've tried so far:
public static void main(String[] args) {
Scanner scanner = null;
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("Start:")) {
String time = line.substring(6);
}
if (line.matches("Items:") && scanner.hasNextLine()) {
String items = line;
}
}
}
[Updated Answer] So the other answer on this question is helpful if the exact words are know that are to be ignored but when there is a big file with lot of lines than this solution will be more accurate.
public static void main(String[] args) {
// TODO Auto-generated method stub
String line = "";
String[] parts = null;
HashMap<String, String> hashmap=new HashMap<String, String>();
try {
BufferedReader br = new BufferedReader(new FileReader("Zoo.txt"));
//line = br.readLine();
while (line != null) {
line = br.readLine();
//System.out.println(line.toString());
if(line!=null){
//System.out.println(line);
if(line.contains("Item")&& line.substring(0, 5).compareTo("Item ")==0){
addToHashMap(line,hashmap);
System.out.println(line);
}
}
}
br.close();
}catch(IOException ioe){
System.err.println(ioe.getMessage());
}
}
private static void addToHashMap(String line, HashMap<String,String> hashMap) {
// TODO Auto-generated method stub
Random random=new Random();
hashMap.put(Integer.toString(random.nextInt(100)), line);
}
The following code should work:
public static void main(String[] args) {
Scanner scanner = new Scanner(TestCdllLogger.class.getResourceAsStream("/test.txt"));
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("Start:") || line.startsWith("End:") || line.startsWith("Items:") || line.startsWith(" ") ||line.isEmpty() ) {
continue;
}
System.out.println(line);
}
}
it ignores all lines starts with Start:, End:, Items: and blank or emty lines.
I know that the code write the lines to stdout and not to a file, but this can changed by your own

Reading and comparing text file line

I have a simple login program and my very simple unsecure database is text file, which is this
mohammed
badpassword1
fahad
badpassword2
saad
Badpassword3
faisal
badpassword4
jack
badpasswod5
and I have this code reading every line in a text file and print it
I just want to pass the username and get it password which is the next line but I couldn't
I tried to store it in array and get the password from next element from the username but all the elements are NULL, I don't know why
can I get some help?
public static void main(String[] args) throws Exception{
try {
FileReader reader = new FileReader("/Users/mohammed/Downloads/testFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = new String();
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
I know this might be a little stupid solution, but it should work.
public class User {
private String username;
private String password;
// getters, setters, toString
}
....
public static void main(String[] args) throws Exception{
try {
FileReader reader = new FileReader("/Users/mohammed/Downloads/testFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line = new String();
// let's have this one to hold users
List<User> users = new ArrayList<>();
int index = 1;
User user = new User();
while ((line = bufferedReader.readLine()) != null) {
now we will read line by line, create User objects and put them into the list
System.out.println(line);
if (index > 2) {
// means you are reading the third line, so that's the name of the next user
users.add(user); // save previous user
user = new User(); // object to hold new one
index = 1; // reset index
}
if (index == 1) {
user.setUserName(line);
}
if (index == 2) {
user.setPassword(line);
}
index++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
// and once you have all the users in the list you can do whatever you need
//e.g. print all users
users.forEach(System.out::println);
// find the user you need, e.g. with name 'fahad'
final User fahad = users.stream().filter(u -> { return u.getUserName().equals("fahad")}).findFirst();
System.out.println(fahad.getPassword()); // for instance
}
Compare the line you currently read to the line you are looking for (username) and print the next one
public static void main(String[] args) throws Exception{
try {
FileReader reader = new FileReader("/Users/mohammed/Downloads/testFile.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String username="mohammed";
String line = new String();
while ((line = bufferedReader.readLine()) != null)
if(line.equals(username){
System.out.println(bufferedReader.readLine());
break;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Java read certain line from txt file

I want to read the 2nd line of text from a file and have that put into an array. I already have it working on the first line.
[ Code removed as requested ]
The while loop above shows how I read and save the 1st line of the text file into an array. I wish to repeat this process from the 2nd line only into a different array.
File Content:
Sofa,Armchair,Computer Desk,Coffee Table,TV Stand,Cushion,Bed,Mattress,Duvet,Pillow
599.99,229.99,129.99,40.00,37.00,08.00,145.00,299.99,24.99,09.99
Just get rid of the first readLine() call, and move the String.split() call into the loop.
Simply use the BufferedReader class to read the entire file and then manipulate the String output.
Something along these lines
public static String readFile(String fileName) throws IOException {
String toReturn = "";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader("test.txt"));
while ((sCurrentLine = br.readLine()) != null) {
toReturn = toReturn+"\n"+sCurrentLine;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null)br.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
return toReturn;
}
would yield a String which can then be easily used.
public static void main(String[] args)
{
String filePath = args[0];
String[] lineElements = getLine(filePath,2).split(",");
}
public static String getLine(String path,int line)
{
List<String> cases = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader(path));
String currLine = "";
while((currLine = br.readLine()) != null){
cases.add(currLine);
}
}catch(IOException ex){
ex.printStackTrace();
}
return cases.get(line - 1);//2nd line
}

How to print lines from a file that contain a specific word using java?

How to print lines from a file that contain a specific word using java ?
Want to create a simple utility that allows to find a word in a file and prints the complete line in which given word is present.
I have done this much to count the occurence but don't knoe hoe to print the line containing it...
import java.io.*;
public class SearchThe {
public static void main(String args[])
{
try
{
String stringSearch = "System";
BufferedReader bf = new BufferedReader(new FileReader("d:/sh/test.txt"));
int linecount = 0;
String line;
System.out.println("Searching for " + stringSearch + " in file...");
while (( line = bf.readLine()) != null)
{
linecount++;
int indexfound = line.indexOf(stringSearch);
if (indexfound > -1)
{
System.out.println("Word is at position " + indexfound + " on line " + linecount);
}
}
bf.close();
}
catch (IOException e)
{
System.out.println("IO Error Occurred: " + e.toString());
}
}
}
Suppose you are reading from a file named file1.txt Then you can use the following code to print all the lines which contains a specific word. And lets say you are searching for the word "foo".
import java.util.*;
import java.io.*;
public class Classname
{
public static void main(String args[])
{
File file =new File("file1.txt");
Scanner in = null;
try {
in = new Scanner(file);
while(in.hasNext())
{
String line=in.nextLine();
if(line.contains("foo"))
System.out.println(line);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
Hope this code helps.
public static void grep(Reader inReader, String searchFor) throws IOException {
BufferedReader reader = null;
try {
reader = new BufferedReader(inReader);
String line;
while ((line = reader.readLine()) != null) {
if (line.contains(searchFor)) {
System.out.println(line);
}
}
} finally {
if (reader != null) {
reader.close();
}
}
}
Usage:
grep(new FileReader("file.txt"), "GrepMe");
Have a look at BufferedReader or Scanner for reading the file.
To check if a String contains a word use contains from the String-class.
If you show some effort I'm willing to help you out more.
you'll need to do something like this
public void readfile(){
try {
BufferedReader br;
String line;
InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream("file path"), "UTF-8");
br = new BufferedReader(inputStreamReader);
while ((line = br.readLine()) != null) {
if (line.contains("the thing I'm looking for")) {
//do something
}
//or do this
if(line.matches("some regular expression")){
//do something
}
}
// Done with the file
br.close();
br = null;
}
catch (Exception ex) {
ex.printStackTrace();
}
}

Categories

Resources