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.
Related
package com;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import com.opencsv.CSVWriter;
import com.opencsv.CSVReader;
public class Sample2 {
public static void main(String args[]) throws IOException
{
CSVReader csvReader = null;
String[] employeeDetails ;
CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv",true));
csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
try
{
employeeDetails = csvReader.readNext();
while ((employeeDetails = csvReader.readNext()) != null ) {
System.out.println(Arrays.toString(employeeDetails));
csvWriter.writeNext(employeeDetails);
}
}catch(Exception ee)
{
ee.printStackTrace();
}
}
}
I have my above java code
It read data from source.csv file and also display in the console .
It created myfile.csv ,but same contents it didn't write in the csv file
Anyone have any idea on this
CSVWriter implements Flushable.Working Solution is already present in #Stephan Hogenboom's answer. I will answer why didn't it write in your case,
From the javadocs of Flushable interface,
A Flushable is a destination of data that can be flushed. The flush
method is invoked to write any buffered output to the underlying
stream.
For performance reasons, all data is to be written into a Buffer instead of File temporarily. Once you call the flush() method, it flushes the data already present in the buffer into your file(this is where disk I/O happens, not when you call writeNext() ).
As mentioned on doc of flush() in java.io.Writer.
Flushes the stream. If the stream has saved any characters from the
various write() methods in a buffer, write them immediately to their
intended destination.
The issue is that you don't close your output resources, try this code:
public static void main(String args[]) throws IOException {
String[] employeeDetails;
try (CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv", true));
CSVReader csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
) {
while ((employeeDetails = csvReader.readNext()) != null) {
System.out.println(Arrays.toString(employeeDetails));
csvWriter.writeNext(employeeDetails);
}
}
catch (Exception ee) {
ee.printStackTrace(); //perhaps you should also log the error?
}
}
Also take a look at this question Is closing the resources always important?
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.
Here From the start() method i called the loadMap(filename) method with a text file.But i don't know why though the loadMap() is called but the FileReader and BufferedReader doesn't working. and the text commented below this two File reader's Statement
System.out.print("INside loadMap()"); doesn't printing in the console and the text File isn't reading. What's the problem here occur actually? Help someone please.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
public class DemoClass {
public static void main(String[] args) {
start();
}
public static void start() {
try {
System.out.print("Pobon File Inside");
loadMap("data\\map1.txt");
} catch (Exception e) {
// TODO: handle exception
}
}
private static void loadMap(String filename) throws IOException {
ArrayList lines = new ArrayList();
FileReader fReader = new FileReader(filename);
BufferedReader reader = new BufferedReader(fReader);
System.out.print("INside loadMap()");
while (true) {
String line = reader.readLine();
if (line == null) {
reader.close();
break;
}
if (!line.startsWith("!")) {
lines.add(line);
}
}
System.out.print("INside loadMap()");
}
}
If System.out.print("INside loadMap()") is never called, then an IOException must be thrown when creating the FileReader.
In other words, the file you entered as the parameter when calling loadMap() (data\map1.txt) doesn't exist. You should consider retrieving the file in a different manner, such as placing it in a source folder and then calling getClass().getResource()
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.