Here i have written a program. I want to get input by a scanner from system. Then I want to show output from file. But after giving input , a message " The file is modyfied by another program " is shown. But i cannot see anything in this file. Please give me a suggestion to solve the problem.
package eighthLecture;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Filetester {
public static void main(String[] args) {
File outFile = new File("C:/Users/nafiulislam/Desktop/naficlass.txt");
try {
FileWriter fileWriter=new FileWriter(outFile);
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String tempString = scanner.nextLine();
System.out.println(tempString);
fileWriter.write(tempString);
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Related
I've finally gotten around to learning Java and I'm trying to write an interpreter for an esolang. I looked up a few tutorials and wrote this code.
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.Files;
import java.util.Scanner;
import java.util.List;
import java.util.ArrayList;
public class NDBall {
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
String input = scanner.nextLine();
Path path = Paths.get(input);
List<String> code = new ArrayList<String>();
code = Files.readAllLines(path);
}
}
However, the readAllLines function keeps giving me an error, and I don't know why. It won't tell me what the error is, and everything else seems fine. I'm doing it exactly as the tutorials I looked up told me.
Is there some mistake I made?
The below code will work for you. have hard coded the path so escape characters are taken care of:
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Solution {
public static Scanner scanner = new Scanner(System.in);
public static void main(String args[]) {
String input = scanner.nextLine();
Path path = Paths.get("C:\\Users\\xyz\\Desktop\\imp.txt");
List<String> code = new ArrayList<String>();
try {
code = Files.readAllLines(path, StandardCharsets.UTF_8);
code.stream().forEach(System.out::println);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Let's say I have theese words in a text file
Dictionary.txt
artificial
intelligence
abbreviation
hybrid
hysteresis
illuminance
identity
inaccuracy
impedance
impenetrable
imperfection
impossible
independent
How can I make each word a different object and print them on the console?
You can simple use Scanner.nextLine(); function.
Here is the following code which can help
also import the libraries
import java.util.Scanner;
import java.io.File;
import java.util.Arrays;
Use following code:-
String []words = new String[1];
try{
File file = new File("/path/to/Dictionary.txt");
Scanner scan = new Scanner(file);
int i=0;
while(scan.hasNextLine()){
words[i]=scan.nextLine();
i++;
words = Arrays.copyOf(words,words.legnth+1); // Increasing legnth of array with 1
}
}
catch(Exception e){
System.out.println(e);
}
You must go and research on Scanner class
This is a very simple solution using Files:
package org.kodejava.io;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
public class ReadFileAsListDemo {
public static void main(String[] args) {
ReadFileAsListDemo demo = new ReadFileAsListDemo();
demo.readFileAsList();
}
private void readFileAsList() {
String fileName = "Dictionary.txt";
try {
URI uri = Objects.requireNonNull(this.getClass().getResource(fileName)).toURI();
List<String> lines = Files.readAllLines(Paths.get(uri),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Source: https://kodejava.org/how-do-i-read-all-lines-from-a-file/
This is another neat solution using buffered reader:
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* BufferedReader and Scanner can be used to read
line by line from any File or
* console in Java.
* This Java program
demonstrate line by line reading using BufferedReader in Java
*
* #author Javin Paul
*/
public class BufferedReaderExample {
public static void main(String args[]) {
//reading file line by line in Java using BufferedReader
FileInputStream fis = null;
BufferedReader reader = null;
try {
fis = new FileInputStream("C:/sample.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading
File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
System.out.println(line);
line = reader.readLine();
}
} catch (FileNotFoundException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
reader.close();
fis.close();
} catch (IOException ex) {
Logger.getLogger(BufferedReaderExample.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Source: https://javarevisited.blogspot.com/2012/07/read-file-line-by-line-java-example-scanner.html#axzz7lrQcYlyy
These are all good answers. The OP didn't state what release of Java they require, but in modern Java I'd just use:
import java.nio.file.*;
public class x {
public static void main(String[] args) throws java.io.IOException {
Files.lines(Path.of("/path/to/Dictionary.txt")).forEach(System.out::println);
}
}
I don't know how to read the last line from the file so it will also be saved in waterlevel.
I have to make in addition to the code a strukogram.
import java.util.Scanner;
import java.io.FileWriter;
import java.ioException;
import java.io.FileNotFoundException;
import java.io.FileReader;
public class Dam{
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
FileWriter fw;
FileReader fr;
int waterLevel;
String text;
do {
System.out.println("give the current water level");
try {
fw = new FileWriter("waterLevel.txt");
text = sc.nextInt()+ "\n";
fw.write(text,0,text.length());
fw.flush();
fw.close;
} catch (IOException e) {
e.printStackTrace();
}
} while (waterLevel < 15);
System.out.println("warning");
}
}
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 5 years ago.
I have recently started learning about file handling in java. However, in this code (down below), I am trying to close the file at the end of all the reading and writing but am facing an error in doing it this way.
package trycatch;
import java.util.Scanner;
import org.omg.CORBA.DataInputStream;
import java.*;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
public class Source {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
try {
File f = new File("record.txt");
FileOutputStream writing = new FileOutputStream(f);
DataOutputStream write = new DataOutputStream(writing);
write.writeUTF("What are the things that you want to do");
String str;
FileInputStream reading = new FileInputStream(f);
java.io.DataInputStream read = new java.io.DataInputStream(reading);
str = read.readUTF();
System.out.println(str);
}
catch(FileNotFoundException e) {
System.out.println("The system collapsed");
}
finally {
write.close(); // write cannot be resolved
read.close(); // read cannot be resolved
}
input.close();
}
}
I am trying out the finally keyword but can you tell me why my IDE cannot recognize read and write when I write it there?
write cannot be resolved
Your read and write fields are local to try block, finally can't access then.Initialize it outside of try.
Try it like that:
package trycatch;
import java.util.Scanner;
import org.omg.CORBA.DataInputStream;
import java.*;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Writer;
public class Source {
public static void main(String[] args) throws Exception {
Scanner input = new Scanner(System.in);
DataOutputStream write = null;
java.io.DataInputStream read = null;
try {
File f = new File("record.txt");
FileOutputStream writing = new FileOutputStream(f);
write = new DataOutputStream(writing);
write.writeUTF("What are the things that you want to do");
String str;
FileInputStream reading = new FileInputStream(f);
read = new java.io.DataInputStream(reading);
str = read.readUTF();
System.out.println(str);
}
catch(FileNotFoundException e) {
System.out.println("The system collapsed");
}
finally {
if (write != null)
write.close(); // write cannot be resolved
if (read != null)
read.close(); // read cannot be resolved
}
input.close();
}
}
You are declaring write inside the try-block. It can't be resolved inside the finally block as this is a different scope.
You need to declare write before the try-block to make it accessible in finally:
DataOutputStream write = null;
try {
...
write = new DataOutputStream(writing);
...
} finally {
if (write != null) {
write.close();
}
}
With recent versions of Java you could/should use the try-with-resource construct to ensure proper resource handling. With this you can omit the finally-block and the JVM will take care of closing your resources when the try-block is left:
try (DataOutputStream write = new DataOutputStream(writing)) {
...
}
write and read are created in the try block and their scope is only in the block. Move the declaration where you are declaring input and it should work.
I am a beginner in Java and trying to learn the basics of FileInputStream and FileOutputStream. I was able to successfully write the data to the file but unable to read it. Here is my code. Could you please let me know, if I am missing something to read the data.
Application.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class Application {
public static void main(String[] args) throws FileNotFoundException {
try(FileOutputStream fs = new FileOutputStream("testdata.txt")){
ObjectOutputStream os = new ObjectOutputStream(fs);
MathematicalOperation mo = new MathematicalOperation();
os.writeObject(mo);
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
ReadingFile.Java
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
public class ReadDataFromFile {
public static void main(String[] args) throws FileNotFoundException{
try(FileInputStream fi = new FileInputStream("testdata.txt")){
ObjectInputStream oi = new ObjectInputStream(fi);
MathematicalOperation mo= (MathematicalOperation) oi.readObject();
System.out.println(mo);
oi.close();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
If you're trying to read the content of the .txt file, just use FileInputStream class.
Also, it would be of great help if you coul
While writing to the file "testdata.txt" you are passing object of MathematicalOperation class, you can set values of the class members before writing file (e.g. mo.setXXX()) and when you are reading that object from text file you can get those values using the return object of MathematicalOperation (e.g. mo.getXXX()) and before printing the object please override toString() method in your MathematicalOperation class to display the correct values of all fields of the class.