Text File error Scanner - java

I'm writing code which deletes a word out of a text file when the user inputs it but I cant seem to get the scanner part to work
public static void Option2Method() throws IOException
{
File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
Scanner writer =new Scanner(tempFile);
String currentLine;
while((currentLine = reader.nextLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.print(currentLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}

Scanner is not meant to write files, hence does not have a write() method. You can use BufferedWriterinstead.
Example:
public static void Option2Method() throws IOException {
File inputFile = new File("wordlist.txt");
FileWriter fstream = new FileWriter("TempWordlist.txt", true);
BufferedWriter writer = new BufferedWriter(fstream);
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.write(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Using PrintWriter:
File inputFile = new File("wordlist.txt");
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("TempWordlist.txt", true)));
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.print(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);

Scanner doesn't have a print method. It is used to scan a file and read data from it.
If you want to write to a file, use this or that or just google "java write to file"

Related

How to delete and override a file in java?

I want to rename and delete "products2.txt" to "products.txt".
if I test with another files "test1" and "test2", in the same directory, will work fine, but with my filles "products" and "products2", doesn't work, not even to delete the file with file.delete();
try{
File file = new File("C:\\Users\\J3TyX\\Desktop\\proiect JAVA PENTA\\products.txt");
Scanner sc = new Scanner(file);
File tempFile = new File("C:\\Users\\J3TyX\\Desktop\\proiect JAVA PENTA\\products2.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
System.out.println("ID number:");
int delete = in.nextInt();
String lineToRemove = Objects.toString(delete,null);
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
String trimmLine[] = trimmedLine.split(" ");
String part1 = trimmLine[0];
if(!part1.equals(lineToRemove)) {
writer.write(currentLine + System.getProperty("line.separator"));
}
}
writer.flush();
writer.close();
reader.close();
sc.close();
file.delete();
tempFile.renameTo(file);
}catch (IOException e){
e.printStackTrace();
}

Based on condition txt file divided into two files in java

My target is i have one txt file it contains some line of text. in this i have two words i.e A and 1. if line has "A" letter then next lines goto one file until next line contain "1" and if line contain "1" then next lines goto other file until "A" find.
Input file like follows
A
rahu
pahdu
jhaani
1
hjsdh
dhj
A
jiko
raju
A
tenk
kouou
I am expecting output
A.txt contain
rahu
pahdu
jhaani
Same
1.txt
My code
{
fis = new FileInputStream("E:\\Input.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
if(line.contains("LETTER00~VSAQCCCC~H~")) {
line = reader.readLine();
System.out.println(line);
}
else {
line= reader.readLine();
}
}
}
You could just repoint your FileOutputStream whenever you find a 1 or A.
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("in.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fosA = new FileOutputStream("out_A.txt");
FileOutputStream fos1 = new FileOutputStream("out_1.txt");
FileOutputStream fos = null;
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while (line != null) {
System.out.println(line);
if(line.equals("A"))
{
fos = fosA;
line = reader.readLine();
continue;
}
if(line.equals("1"))
{
fos = fos1;
line = reader.readLine();
continue;
}
fos.write(line.getBytes());
fos.write('\n');
fos.flush();
line = reader.readLine();
}
fos.close();
fosA.close();
fos1.close();
}
You can do something like this.
System.out.println("Reading File line by line using
BufferedReader");
String inputFIle = "";
String line;
boolean flag = false;
// String line = reader.readLine();
while ((line = reader.readLine()) != null) {
if (line.trim().equalsIgnoreCase("A")) {
inputFIle = "A.txt";
} else if(line.trim().equalsIgnoreCase("1")){
inputFIle = "1.txt";
}
else{
write(line, inputFIle);
}
}
You can do something like this
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new FileReader("Input.txt"));
boolean isFound = false;
List<String> main_list = new ArrayList<>();
List<String> sub_list = new ArrayList<>();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains("A")) {
isFound = true;
} else if(line.contains("1")) {
isFound = false;
for (String aSub_list : sub_list) {
main_list.add(aSub_list);
}
sub_list.clear();
}
if(isFound && !line.contains("A")) {
sub_list.add(line);
}
}
for (String aMain_list : main_list) {
System.out.println(aMain_list);
}
}

How to given a fixed path to eclipse

Code:
InputStream inputStream = System.in;
InputReader in = new InputReader(inputStream);
How could I modify this code to take a file from a fixed location?
Equivalent scanner example:
Scanner in = new Scanner(new InputStreamReader(System.in));
Scanner in = new Scanner(new FileReader("C:\\Users\\Max\\Desktop\\yes.txt"));
if you only want the whole text in one string than you can use the FileInputStream
FileInputStream inputStream = new FileInputStream("foo.txt");
try {
String everything = IOUtils.toString(inputStream);
} finally {
inputStream.close();
}
if you want to read the file line bye line use the BufferdReader in Connection with StringBuilder
BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
}finally {
br.close();
}
Note:
The examples are taken from #Knubo and the whole answer and further Information can be found here
To read file using Scanner class.
Try this.
Scanner input=null;
try{
input=new Scanner(new File("your_file_path\yes.txt"));
} catch(Exception ex){
System.out.println(ex.getMessage());
}
while(input.hasNext()){
System.out.println(input.next());
}
input.close();

Cannot find symbol when using bufferwriter.readline()

I'm trying to learn java but I don't know why I'm getting there errors.What I basically want is that user will input new characters and will be written to the file as long it is not the word "stop"(program terminates at this point).
Can you guys help me?
import java.io.*;
import java.util.*;
class FileHandling{
public static void main(String args[]){
System.out.println("Enter a File name");
Scanner input = new Scanner(System.in);
String file1Name = input.next();
if(file1Name == null){
return;
}
try{
File f1 = new File(file1Name+".txt");
f1.createNewFile();
String file1NameData = "";
String content = input.next();
FileWriter fileWritter = new FileWriter(f1.getName(),true);
BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
bufferWritter.write(file1NameData);
bufferWritter.close();
}catch(Exception e){
System.out.println("Error : " );
e.printStackTrace();
}
}
}
You are trying to read from writer which you can't. You already have scanner and using it, you could read form System input i.e. Keyboard.
Change your line like:
From
while(!(file1NameData=bufferWritter.readLine()).equalsIgnoreCase("stop")){
To
while(!(file1NameData=input.nextLine()).equalsIgnoreCase("stop")){
You are trying to read from your output, not your input
while(!input.next().equalsIgnoreCase("stop")){
bufferWritter.write(file1NameData + System.getProperty("line.separator"));
}
public static void main(String[] args) throws Exception {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(new File("test.txt"), true))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (line.equals("stop"))
break;
writer.write(line);
writer.newLine();
}
}
}
}

readFile method does not show results at console

This is my question :
a method readLine that reads a line from the file specified in fileName and returns the line a String.
What I am trying to do is I read and write some info into text file using eclipse. And here are my codes :
public class FileController {
private String fileName;
public FileController(){
String fileName = "student.txt";
}
public FileController(String fileName){
this.fileName = fileName;
}
public String readLine(){
String line ="";
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line;
}
public void writeLine(String input){
try{
FileWriter fw = new FileWriter(fileName,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.println(input);
outFile.close();
}catch(IOException exception){
System.out.println(exception);
}
}
public static void main (String [] args){
FileController fc = new FileController("student.txt");
String input = "1234567H;Gabriel;23/12/1994;56;67;87";
fc.readLine();
fc.writeLine(input);
}
This works perfectly by adding the record into the text file. However, the console there doesn't shows the result. So from what I know it's the mistake was at readLine(). When I used void it works perfectly. But the question requests me to return a String. Anybody know how to solve this?
when I do println within the while loop there's record stored in there. I guess the programme took the String file= ""; this line and return the result. So how can I take the result of line in while loop and replace with the initialization?
You are overwriting the line in while loop:
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
So this means that only last line will get passed to student [most likely blank line] and it might not print anything or even an exception might come. Use StringBuffer and append the string and then return that.
EDIT:
Try this.
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}
EDIT:
If above code also returns blank then most likely issue is Strudent "toString()" method. It might be returning blank.
EDIT:
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
line.append("\n");
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}

Categories