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.
Related
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);
}
}
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.
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();
}
}
}
I have gone through all the related posts in this forum and also googled but not found the exact answer.
When running the below code, I get following error:
The constructor BufferedWriter(FileWriter) is undefined
The constructor FileWriter(String) is undefined
public class FileWriter {
public static void main(String[] args) {
BufferedWriter f = null;
try
{
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e)
{
System.out.println(e);
}
finally
{
f.close();
}
}
}
I guess you want to use java.io.FileWriter class of java but you redefine it. You can rename your class to something else more meaningful.
You have to import your used classes like BufferedWriter. That's why you get your undefined errors.
Also it is a good practice to check if the writer f is null before closing:
import java.io.FileWriter;
import java.io.BufferedWriter;
import java.io.IOException;
public class FileWriterExample {
public static void main(String[] args) {
BufferedWriter f = null;
try {
f = new BufferedWriter(new FileWriter("C:\\A.txt"));
f.write("Hello World");
}
catch(IOException e) {
System.out.println(e);
}
finally {
if (f != null)
f.close();
}
}
}
Your class is called FileWriter which conflicts with the name of the java.io.FileWriter. Rename your class something else and then explicitly import the java.io.FileWriter and java.io.BufferedWriter classes.
import java.io.FileWriter;
import java.io.BufferedWriter;
I would also suggest using a more modern idiom: try-with-resources, which automatically closes the writer for you. It's terser and cleaner.
public class Example {
public static void main(String... args) throws Exception {
try (BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\A.txt")) {
writer.write("Hello World");
}
}
}
use these steps. This is the correct and easy way to use buffered writer.
1.create File object.
File f = new File(C://A.txt);
create file writer object.
FileWriter fr = new FileWriter(f);
create Buffered writer .
BufferedWriter bw = new BufferedWriter(fr);
4.then you can easily write to the file like below.
bw.write("Hello World");
hope this will be help to you
remember to import
java.io.FileWriter;
java.io.BufferedWriter;
java.io.IOException;
those packages will be automatically suggest if you are using ide like netbeans.
import java.io.FileOutputStream;
import java.io.File;
public class AppendBinaryFile
{
public static void main (String[] args)
{
FileOutputStream toFile = null;
try
{
toFile = new FileOutputStream(new File("numbers.dat"), true);
toFile.write(15);
toFile.write(30);
toFile.close();
}
catch (Exception e)
{
}
}
}
I run another program to get the data from a binary file after running the program but data in the binary file does not change. What is wrong with the code?
You need to close your file output stream I believe.