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();
...
}
Related
I'm trying to prompt the user to input the name a file they'd like to write to, create that .txt file and then write the qualifying lines of text into that file and save it. inside the do while, it seems to be skipping over the user input for the name of the file they'd like to save to, looping back around and then getting a FileNotFoundException, and it shouldn't even be looking for a file.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you
would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
do {
System.out.println("please enter a name for the file to write to
(end with .txt): ");
String out = user.nextLine(); //PROBLEM HERE! SKIPS USER INPUT
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0],
Integer.parseInt(elements[1]),
Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]),
Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost &&
bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
I just needed to skip a line before the loop began.
import java.util.*;
import java.io.*;
public class Main {
public static void main(String[] args) {
Scanner user = new Scanner(System.in);
Scanner docInName = null;
PrintWriter docOutName = null;
do {
System.out.println("Please enter the filename of the file you would like to read from: ");
try {
docInName = new Scanner(new File(user.nextLine()));
} catch (FileNotFoundException e) {
System.out.println("File not found!");
}
} while (docInName == null);
int lineNum = docInName.nextInt();
BikePart[] bp = new BikePart[lineNum];
System.out.println("please enter the max cost for a part: ");
int cost = user.nextInt();
user.nextLine(); //SOLUTION HERE
do {
System.out.println("please enter a name for the file to write to (end with .txt): ");
String out = user.nextLine();
try {
docOutName = new PrintWriter(out);
for (int i = 0; i < lineNum; i++) {
String line = docInName.nextLine();
String[] elements = line.split(",");
bp[i] = new BikePart(elements[0], Integer.parseInt(elements[1]), Double.parseDouble(elements[2]),
Double.parseDouble(elements[3]), Boolean.parseBoolean(elements[4]));
double temp = Double.parseDouble(elements[3]);
if ((temp < cost && bp[i].isOnSale() == true)
|| (bp[i].getListPrice() < cost && bp[i].isOnSale() == false)) {
docOutName.write(line);
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
} while (docOutName == null);
user.close();
}
}
import java.util.*;
import java.io.*;
public class Events{
File output = new File ("chinese.txt");
static ArrayList <Event> events = new ArrayList <Event>();
public static void main(String[]args){
try{
Scanner sc = new Scanner(new File("events.txt"));
File output = new File("chinese.txt");
PrintWriter printer = new PrintWriter(output);
while(sc.hasNext()){
//String temp = sc.nextLine();
//System.out.println(temp);
int num = sc.nextInt();
String desc = sc.nextLine();
events.add(new Event(num,desc));
}
//break;
}
catch(Exception e){
System.out.println("Invalid file");
}
Collections.sort(events);
for(int i = 0; i<events.size();i++){
System.out.println(events.get(i));
printer.println(events.get(i).toString());
}
`}
}'
I create a printer object and a new file object to print the contents of an arraylist but inside my for loop it can't find the symbol and I have tried everything to fix it with no luck.
printer is declared inside the try block but you are trying to use it outside it. Include the for loop within the try block and it should solve your problem
import java.util.*;
import java.io.*;
public class Events{
File output = new File ("chinese.txt");
static ArrayList <Event> events = new ArrayList <Event>();
public static void main(String[]args){
try{
Scanner sc = new Scanner(new File("events.txt"));
File output = new File("chinese.txt");
PrintWriter printer = new PrintWriter(output);
while(sc.hasNext()){
//String temp = sc.nextLine();
//System.out.println(temp);
int num = sc.nextInt();
String desc = sc.nextLine();
events.add(new Event(num,desc));
}
//break;
Collections.sort(events);
for(int i = 0; i<events.size();i++){
System.out.println(events.get(i));
printer.println(events.get(i).toString());
}
}
catch(Exception e){
System.out.println("Invalid file");
}
}
}
You need to declare printer before the try block, otherwise the scope of printer is limited to the try block. This will fix it:
public static void main(String[]args){
PrintWriter printer = null;
try{
Scanner sc = new Scanner(new File("events.txt"));
File output = new File("chinese.txt");
printer = new PrintWriter(output);
while(sc.hasNext()){
//String temp = sc.nextLine();
//System.out.println(temp);
int num = sc.nextInt();
String desc = sc.nextLine();
events.add(new Event(num,desc));
}
//break;
}
catch(Exception e){
System.out.println("Invalid file");
}
Collections.sort(events);
for(int i = 0; i<events.size();i++){
System.out.println(events.get(i));
printer.println(events.get(i).toString());
}
}
I'm trying to search a certain string from an input file. Firstly, the code stores data from input file and then it searches the user input data in the text file, but when i try to print one of the variables it ends up being null.
public class Test {
public static void main(String args[])throws IOException, FileNotFoundException {
BufferedReader input = null;
PrintWriter output = null;
try {
input = new BufferedReader (new FileReader ("kolej.txt"));
Scanner in = new Scanner(System.in);
in.useDelimiter("\n");
int index = 0;
String indata = null;
System.out.println("UITM College and Non-Residents Registration System");
System.out.println("Enter your student id: ");
String matrix = in.next();
UITM student[] = new UITM[10];
//storing data into array
while ((indata = input.readLine())!= null) {
StringTokenizer st = new StringTokenizer(indata,";");
student[index] = new Kolej(st.nextToken(), st.nextToken(), st.nextToken(), Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken()), st.nextToken(),Integer.parseInt(st.nextToken())) ;
index++;
}
//searching
Scanner txtscan = new Scanner(new File("kolej.txt"));
while(txtscan.hasNextLine()) {
matrix = txtscan.nextLine();
if(matrix.indexOf("word") != -1) {
System.out.println(student[0].getName());
}
}
input.close();
output.close();
}
catch (FileNotFoundException fnfe) {
System.out.println("File not found");
}
catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
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);
}
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) {
}
}
}
}