reading a specific information in file - java

I want to read this file using Scanner, but not all the information, only the things after semicolon like 10, warrior, John Smith and so on.
currhp: 10
type: Warrior
name: John Smith
items:
Stick,1,2,10,5
gold: 10
type: Wizard
I tried to solve it but i couldn't.
Scanner infile;
Scanner inp = new Scanner(System.in);
try {
infile = new Scanner(new File("player_save.txt"));
} catch (FileNotFoundException o) {
System.out.println(o); return; }
while (infile.hasNextLine()) {
System.out.println(infile.nextLine());
}

You need to open file, read line by line and then split each line and use the chunk of the line that you wish to do further processing on it.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile{
public static void main(String[] args) throws IOException {
//fix the URL to where your file is located.
try (BufferedReader br = new BufferedReader(new FileReader("C:\\player_save.txt"))) {
String line;
while ((line = br.readLine()) != null) {
if(line.length() > 0) {
if(line.contains(":")) {
System.out.println("Before colon >> " + line.split(":")[0]);
} else {
//no column found taking the whole line
System.out.println("whole line having no coln: " + line);
}
}
}
} catch(FileNotFoundException fnfe) {
//Handle scenario where the file does not exist
} catch(IOException ie) {
//Handle other File I/O exceptions here
}
}
}

You can do something like this -
List<String> list= new ArrayList<>();
try(
Scanner scan= new Scanner(new BufferedReader(new FileReader("//your filepath")));
){
while(scan.hasNextLine()){
String s=scan.nextLine();
if(s.contains(":")){
String arr[]=s.split(":");
list.add(arr[1].trim());
}
}
}
catch(Exception e){
System.out.println(e.getMessage());
}
for(String str:list){
System.out.println(str);
}

Related

no such element exception pop ups everytime i use writer method [duplicate]

This question already has an answer here:
How to use java.util.Scanner to correctly read user input from System.in and act on it?
(1 answer)
Closed 1 year ago.
import java.io.IOException;
import java.io.File;
import java.nio.file.Path;
import java.util.Scanner;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.NoSuchElementException;
public class filehandling{
public static void main(String[] args){
Scanner x = new Scanner(System.in);
while(true){
System.out.println("1. write 2. read 3. delete 4. create 5.exit");
System.out.print("Enter choice: ");
int ch = x.nextInt();
if(ch==1){
writer1 var0 = new writer1();
var0.function1();
}
if(ch==2){
reader1 var0 = new reader1();
var0.function2();
}
if(ch==3){
delete1 var0 = new delete1();
var0.function4();
}
if(ch==4){
create1 var0 = new create1();
var0.function3();
}
if(ch==5){
System.out.println("exited, thank you for using program");
x.close();
break;
}
}
}
}
class writer1{
void function1(){
Scanner y = new Scanner(System.in);
System.out.print("Input file name: ");
String path = y.nextLine();
File file = new File("D:\\"+path);
System.out.print("input number of lines: ");
Scanner a = new Scanner(System.in);
int n = a.nextInt();
Scanner z = new Scanner(System.in);
System.out.print("input data: ");
String data = z.nextLine();
FileWriter fr = null;
BufferedWriter br = null;
String datawithnewline = data+System.getProperty("line.separator");
System.out.println(datawithnewline);
try {
for(int i = n; i>0;i--){
try {
fr = new FileWriter(file);
br = new BufferedWriter(fr);
br.write(datawithnewline);
} catch (NoSuchElementException e) {
System.out.println("DONE ");
}
}
} catch (IOException e) {
System.out.print("error");
}
finally{
try{
br.close();
fr.close();
y.close();
z.close();
a.close();
}
catch(IOException e){
System.out.print("Error 2");
}
}
}
}
class reader1{
void function2(){
Scanner y = new Scanner(System.in);
System.out.print("Input file name: ");
String path = y.nextLine();
File file = new File("C:\\Users\\subra\\AppData\\Local\\Temp\\vscodesws_32946\\jdt_ws\\jdt.ls-java-project\\src"+path);
if(file.canRead()){
FileReader fr = null;
BufferedReader br = null;
try{
fr = new FileReader(path);
br = new BufferedReader(fr);
int var = 0;
while(( var=br.read())!= -1){
char text = (char) var;
System.out.print(text);
}
}
catch(IOException e){
System.out.println("Error");
}
finally{
y.close();
if (fr !=null){
try{
fr.close();
}
catch(IOException e){
System.out.println("Error");
}
}
if(br!=null){
try{
br.close();
}
catch(IOException e){
System.out.println("Error");
}
}
}
}
}
}
class create1{
public void function3(){
Scanner var1 = new Scanner(System.in);
System.out.print("Input file name: ");
String var2 = var1.nextLine();
File file = new File("D:\\"+var2);
try {
boolean createNewfile = file.createNewFile();
System.out.println("File created: "+createNewfile);
} catch (IOException e) {
System.out.println("Error");
var1.close();
}
}
}
class delete1{
public void function4(){
Scanner y = new Scanner(System.in);
System.out.print("Input file name");
String path = y.nextLine();
Path path1 = Path.of(path);
String path2 = path1.toString();
File file = new File(path2);
if(file.canRead()){
boolean delete = file.delete();
System.out.println("DELETED FILE: "+delete);
}
y.close();
}
}
every time I run this program, it always returns this error, I am actually studying file handling in java so I used this website, I am using visual studio code, I have tried putting br.write(...) part in a try and catch block inside the for loop in writer1 class,
the total interaction in the terminal is
PS C:\Users\subra\AppData\Local\Temp\vscodesws_32946\jdt_ws\jdt.ls-java-project\src> c:; cd 'c:\Users\subra\AppData\Local\Temp\vscodesws_32946\jdt_ws\jdt.ls-java-project\src'; & 'c:\Users\subra\.vscode\extensions\vscjava.vscode-java-debug-0.36.0\scripts\launcher.bat' 'C:\Program Files\Java\jdk-16.0.2\bin\java.exe' '-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=localhost:50835' '--enable-preview' '-XX:+ShowCodeDetailsInExceptionMessages' '-Dfile.encoding=UTF-8' '-cp' 'C:\Users\subra\AppData\Roaming\Code\User\workspaceStorage\3543e469db802eccea9e87de0109e000\redhat.java\jdt_ws\src_c37eea88\bin' 'filehandling'
1. write 2. read 3. delete 4. create 5.exit
Enter choice: 1
Input file name: hi
input number of lines: 5
input data: i love coding
i love coding
1. write 2. read 3. delete 4. create 5.exit
Enter choice: Exception in thread "main" java.util.NoSuchElementException
at java.base/java.util.Scanner.throwFor(Scanner.java:937)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at filehandling.main(filehandling.java:16)
what should I do??
You only should be using one Scanner across all your classes, and only closing it once
Using an example from only one of your classes (classes should be capitalized, and generally don't use numbers)
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
Reader reader = new Reader(sc); // your class. Don't close the Scanner in it
int ch = -1;
while (ch !=5) {
ch = sc.nextInt();
if (ch == 2) {
reader.read();
}
}
sc.close(); // only done once
}
Then update the classes to add a constructor
class Reader {
private Scanner sc;
public Reader(Scanner scanner) {
this.sc = scanner;
}
public void read() {
String filepath = sc.readLine();
...
}

How can I add an line number to my output and detect if a file isn't found?

I have code that is supposed to receive a filename from the user and output the contents in a numbered list like this:
https://imgur.com/a/CGd86xU
Now, I can't seem to be able to add the 1. 2. 3., etc into my output without hardcoding, or how I can try to detect if a file isn't found in the same directory as the code file is in and tell the user such file doesn't exist.
So far the code that I have output the code correctly as shown in the example but minus the numbering the content of the files or distinguishing if the file the user inputs exists.
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter filename");
String fileName = scanner.nextLine();
File f = new File(fileName);
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = null;
System.out.println(""); //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.
while ((readLine = b.readLine()) != null) {
System.out.println(readLine);
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
Note: I'm rather new to code involving files so yeah...
If I understand what you're asking correctly, you want to print line numbers for each line of the file specified by the user.
If so, then you can just add a counter variable when you read the file line by line:
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Q4 {
public static void main(String[] args) throws IOException {
try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter filename");
String fileName = scanner.nextLine();
File f = new File(fileName);
if (!f.exists()) {
System.out.println(fileName + " doesn't exist!");
return;
}
BufferedReader b = new BufferedReader(new FileReader(f));
String readLine = null;
System.out.println(""); //Intended to be empty as to allow the next line. So far that's the only way to get this part it to work.
int counter = 1;
while ((readLine = b.readLine()) != null) {
System.out.println(counter + ": " + readLine);
counter++;
}
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
I also added a check to see if the File exists using the File.exists() method.

How to read from inputFileStream and split each line

I have to read from input file txtfile that look like mark;1001;3;4 there is a ';' between each variable. I know how to read it if it's in separate lines, but I can't read it if its in the same line.
This is how I start:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.nio.Buffer;
public class Try {
public static void main(String[] args) {
String Name;
int ID;
Double quiz1 , quiz2;
try {
FileInputStream fileIN = new FileInputStream("input.txt");
InputStreamReader inputST =new InputStreamReader(fileIN);
BufferedReader bufferRe = new BufferedReader(inputST);
String line;
while ((line = bufferRe.readLine()) != null) {
// I tried many things, but nothing worked for me.
// How could I use split here?
}
} catch (IOException e) {
System.out.println("input is not found ");
}
}
}
Using split is the way to go...
while ( ( line = bufferRe.readLine())!= null) {
for (String splitVal : line.split(";") {
//Do whatever you need to with the splitVal value.
//In you example it iterate 4 times with the values mark 1001 3 4
}
}
The simplest solution, which also works when you want things to work across newlines, is to use a Scanner with ; as its delimiter:
Scanner s = new Scanner(bufferRe);
s.useDelimiter(";");
while (s.hasNext()) {
System.out.println(s.next());
}
-->
mark
1001
3
4
This also allows you to use Scanner methods to eg. easily parse integers.
Just use split method inside loop to get all your data in array.
String[] splited = line.split(";");
while ((line = bufferRe.readLine()) != null) {
for (String retval : line.split(";", 2)) {
System.out.println(retval);
}
}
Output:
mark
1001;3;4
There is one more aproach using StreamTokenizer
try {
FileInputStream fis = new FileInputStream("input.txt");
Reader r = new BufferedReader(new InputStreamReader(fis));
StreamTokenizer st = new StreamTokenizer(r);
List<String> words = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
// print the stream tokens
boolean eof = false;
do {
int token = st.nextToken();
switch (token) {
case StreamTokenizer.TT_EOF:
System.out.println("End of File encountered.");
eof = true;
break;
case StreamTokenizer.TT_EOL:
System.out.println("End of Line encountered.");
break;
case StreamTokenizer.TT_WORD:
words.add(st.sval);
break;
case StreamTokenizer.TT_NUMBER:
numbers.add((int)st.nval);
break;
default:
System.out.println((char) token + " encountered.");
if (token == '!') {
eof = true;
}
}
} while (!eof);
} catch (IOException e) {
e.printStackTrace();
System.out.println("input is not found ");
}

Reverse lines in ArrayList Java

I'm working on a Java program in which I must read the contents of a file and then print each lines reverse. For example the text:
Public Class Helloprinter
Public static void
would print the following after running my reverse program:
retnirPolleh ssalc cilbup
diov citats cilbup
Here's what I got so far:
public static void main(String[] args) throws FileNotFoundException {
// Prompt for the input and output file names
ArrayList<String> list = new ArrayList<String>();
//String reverse = "";
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
String aString = "";
while(in.hasNextLine())
{
String line = in.nextLine();
list.add(line);
}
in.close();
for(int i = 0; i <list.size(); i++)
{
aString = list.get(i);
aString = new StringBuffer(aString).reverse().toString();
out.printf("%s", " " + aString);
}
out.close();
}
}
EDIT:
With Robert's posting it helped put me in the right direction. The problem is that with that is that it doesn't keep the lines.
Public Class Helloprinter
Public static void
becomes after running my program:
retnirPolleh ssalc cilbup diov citats cilbup
it needs to keep the line layout the same. so it should be:
retnirPolleh ssalc cilbup
diov citats cilbup
Your problem is in the line
out.printf("%s", " " + aString);
This doesn't output a newline. I'm also not sure why you are sticking a space in there.
It should be either:
out.println( aString );
Or
out.printf("%s%n", aString);
In your last loop why don't you just iterate through the list backwards? So:
for(int i = 0; i <list.size(); i++)
Becomes:
for(int i = list.size() - 1; i >=0; i--)
It seems like you already know how to read a file, so then call this method for each line.
Note, this is recursion and it's probably not the most efficient but it's simple and it does what you want.
public String reverseString(final String s) {
if (s.length() == 0)
return s;
// move chahctrachter at current position and then put it at the end of the string.
return reverseString(s.substring(1)) + s.charAt(0);
}
Just use a string builder. You were on the right trail. Probably just needed a little help. There is no "one way" to do anything, but you could try something like this:
Note: Here is my output: retnirPolleh ssalc cilbup diov citats cilbup
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
ArrayList<String> myReverseList = null;
System.out.println("Input file: \n");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
System.out.println("Output file: \n");
String outputFileName = input.nextLine();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String text = null;
myReverseList = new ArrayList<String>();
StringBuilder sb = null;
try {
while ((text = br.readLine()) != null) {
sb = new StringBuilder();
for (int i = text.length() - 1; i >= 0; i--) {
sb.append(text.charAt(i));
}
myReverseList.add(sb.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), "utf-8"));
for (String s : myReverseList) {
writer.write("" + s + "\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
}

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