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.
Related
It's not showing any error but the content should be saved to my file, which is not saving...
import java.util.Scanner;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class FileReadLine {
public static void main(String[] args) {
try {
String str;
Scanner sc=new Scanner(System.in);
do {
System.out.println("Enter your lines");
str=sc.nextLine();
FileWriter fw = new FileWriter("C:/test/abcd.txt");
if(!str.equals("stop"))
fw.write(str);
fw.write("\n");
fw.close();
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}
}
}
please correct my code if i am wrong
You are trying to create a new file inside the loop. So it gets overridden. Change the program to create the file once(before loop) and use it inside the loop to write it.
Also do not close the file as soon as you have written it. Use it once you encounter "stop". Close() should be used when you are done with writing into the file.
Try using flush() before close() to send all data in the buffer to the the file.
You must close you FileWriter (fw) out of while loop.
Try below code
public static void main(String[] args) throws IOException {
FileWriter fw = null;
try {
fw = new FileWriter("C:/Users/MYPC/Desktop/abcd.txt");
String str;
Scanner sc = new Scanner(System.in);
do {
System.out.println("Enter your lines");
str = sc.nextLine();
if (!str.equals("stop")){
fw.write(str);
}
fw.write("\n");
} while (!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
// Logger.getLogger(FileReadLine.class.getName()).log(Level.SEVERE,
// null, ex);
}finally{
if(fw != null){
fw.close();
}
}
}
You were closing the writer in every iteration since you are not using braces in the if condition...
Try this solution, is working
try {
String str;
Scanner sc=new Scanner(System.in);
File fw = new File("C:/Users/MYPC/Desktop/abcd.txt");
FileOutputStream fos = new FileOutputStream(fw);
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
do {
System.out.println("Enter your lines");
str=sc.nextLine();
if(!str.equals("stop")) {
bw.write(str);
bw.newLine();
} else {
bw.close();
}
} while(!str.equals("stop"));
} catch (Exception ex) {
System.out.println(ex);
}
In the output file "CMFTSwitchesnew.txt" only has the last line of the input file. I've tested a few different methods such as changing write.println(input.nextLine()) but I'm not sure now where the issue is.
package WorkingWithFiles;
import java.io.*;
import java.util.Scanner;
public class FileIO
{
public static void main(String[] args)
{
File output = new File("CMFTSwitchesNew.txt");
File source = new File("src/CMFTSwitches.txt");
try {
Scanner input = new Scanner(source);
while (input.hasNextLine()) {
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
}
} catch (FileNotFoundException e) {
System.out.println("The file was not found");
}
}
}
try {
PrintWriter write = new PrintWriter(output);
String text = input.nextLine();
write.println(text) // also tried
// write.println(input.nextLine());
write.close();
} catch (Exception e) {
System.out.println("Exception found");
}
You're creating a PrintWriter in each iteration without using the constructor that allows you to tell the PrintWriter to append data at the end of an already existing file. That way you only see the output of the last time the file was written. Either change that to
PrintWriter write = new PrintWriter(output, true);
or instantiate the PrintWriter outside the while-loop and close it after it.
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();
}
}
}
These are the contents of the constructor of a class which is called by the main method.
File f = null;
Scanner s;
try {
f = new File(getClass().getResource("/LOL.txt").toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
try {
s = new Scanner(f);
while(s.hasNextLine()) System.out.println(s.nextLine());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
try {
FileWriter fw = new FileWriter(f.getAbsoluteFile(), false);
BufferedWriter bw = new BufferedWriter(fw);
bw.write("LOL");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
Output in the console:
LOL
The contents of the file remain unchanged even after repeated runs. My IDE is eclipse
You parametrize your FileWriter with boolean append set as false.
Therefore, the same file will be written over every time that given constructor is executed, and "LOL" will be printed in it.
Before printing "LOL", a Scanner reads each line and prints it, hence the LOL printed in our system out.
Also note, you probably want to declare your FileWriter and BufferedWriter out of the try block, so you can flush and close them in a finally block.
This post only contains the initial question, as-is with everything corrected to avoid several resource-related bugs. It assumes Java 6 or lower.
I shouldn't get any upvote so please don't ;)
package so39452286;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
new Main().run();
}
public void run() {
try {
File file = new File(getClass().getResource("/LOL.txt").toURI());
Scanner scanner = null;
try {
scanner = new Scanner(file);
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
} finally {
if (scanner != null) {
scanner.close();
}
}
Writer writer = null; // Holds the main resource, not the wrapping ones.
try {
writer = new FileWriter(file.getAbsolutePath(), false);
BufferedWriter bw = new BufferedWriter(writer);
bw.write("LOL");
bw.flush(); // You forgot to flush. Ok, close() does it, but it's always better to be explicit about it.
} finally {
if (writer != null) {
writer.close();
}
}
} catch (Exception e) {
// Do something with e.
e.printStackTrace(System.err);
}
}
}
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()