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.
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);
}
}
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.
I am new to java, but not coding. I am trying to figure out java because it's part of my class this term and I am having a really hard problem grasping the idea of it and implementing things in java.
my problem Is that I am not sure if I am correctly using the arraylist to grab data from the scan of the file and input it into a arraylist to sort and print at a later time. I am just having issues picking up on java any help would be great since I am new to java.
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.*;
public class MissionCount
{
private static ArrayList<String> list = new ArrayList<String>();
// returns an InputStream that gets data from the named file
private static InputStream getFileInputStream(String fileName) throws Exception {
InputStream inputStream;
try {
inputStream = new FileInputStream(new File(fileName));
}
catch (FileNotFoundException e) { // no file with this name exists
inputStream = null;
throw new Exception("unable to open the file -- " + e.getMessage());
}
return inputStream;
}
public static void main(String[] args) {
if (args.length != 1) {
System.out.println("USage: MissionCount <datafile>");
//System.exit(1);
}
try {
System.out.printf("CS261 - MissionCount - Chad Dreher%n%n");
int crewcount = 0;
int misscount = 0;
InputStream log = getFileInputStream(args[0]);
Scanner sc = new Scanner(log);
sc.useDelimiter(Pattern.compile(",|\n"));
while (sc.hasNext()) {
String crewMember = sc.next();
list.add(crewMember);
String mission = sc.next();
list.add(mission);
}
sc.close();
// Add code to print the report here
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
}
}
InputStream log = getFileInputStream(args[0]);
Change that line to as follows :-
File log = new File(args[0])
that should work!
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.
This there anything wrong with my code? I'm new to Java and i'm trying to import a file into MongoDB. However there is a error that i have no idea what is it. I am using Eclipse.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.util.JSON;
import com.mongodb.util.JSONParseException;
public class readwrite {
public static void main(String[] args) throws FileNotFoundException,IOException,JSONParseException{
Mongo mongo = new Mongo("localhost", 27017);
DB db = mongo.getDB("actualdata");
DBCollection collection = db.getCollection("metadata");
String line = null;
StringBuilder sb = new StringBuilder();
try {
FileInputStream fstream = null;
try {
fstream = new FileInputStream("/home/Output/json1-100000-all");
} catch (FileNotFoundException e) {
e.printStackTrace();
System.out.println("File does not exist, exiting");
return;
}
BufferedReader bufferedReader =
new BufferedReader(new InputStreamReader(fstream));
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
DBObject dbObject;
sb.append(dbObject = (DBObject) JSON.parse(bufferedReader.readLine()));
collection.insert(dbObject);
DBCursor cursorDoc = collection.find();
while (cursorDoc.hasNext()) {
System.out.println(cursorDoc.next());
}
}
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println("Unable to open file");
}
catch(IOException ex) {
System.out.println(
"Error reading file");
}
}
}
This is the error that is displayed
[
Exception in thread "main" com.mongodb.util.JSONParseException:
{
^
at com.mongodb.util.JSONParser.read(JSON.java:272)
at com.mongodb.util.JSONParser.parseObject(JSON.java:230)
at com.mongodb.util.JSONParser.parse(JSON.java:195)
at com.mongodb.util.JSONParser.parse(JSON.java:145)
at com.mongodb.util.JSON.parse(JSON.java:81)
at com.mongodb.util.JSON.parse(JSON.java:66)
at readwrite.main(readwrite.java:45)
It show me this error when i clicked on at com.mongodb.util.JSONParser.read(JSON.java:272) where it says that the Source is not found. The source attachment does not contain the source for the file JSON.class.
I can print the output of BufferedReader if i did not included the conversion of DBObject. Thanks in advance!
1) Didn't you mean to write JSON.parse(line)
instead of JSON.parse(bufferedReader.readLine())) ?
This might cause it to try and parse 'null' at the last iteration
2) If that doesn't help, could you get the exact string value of 'line' on the failed iteration? (this should be easy using debugger or simple printing to system out)
Regards