Here is a method:
private void writeToFile() {
try {
String time = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String name = "dictionaryFile" + time + ".txt";
File dictionaryFile = new File(name);
BufferedWriter writer = new BufferedWriter(new FileWriter(dictionaryFile));
Iterator<String> it = dictionary.keySet().iterator();
while (it.hasNext()){
String line = it.next();
String entryLine = line + " -> " + dictionary.get(line);
writer.write(entryLine);
writer.close();
}
} catch(Exception e)
{
e.printStackTrace();
}
}
And here is error:
java.io.IOException: Stream closed
at java.io.BufferedWriter.ensureOpen(Unknown Source)
at java.io.BufferedWriter.write(Unknown Source)
at java.io.Writer.write(Unknown Source)
at WordQuizz.WordCollection.writeToFile(WordCollection.java:58)
at WordQuizz.WordCollection.actionPerformed(WordCollection.java:44)
Can anyone help me to solve this issue? if I just try to sysout print entryLine then there is no error. May be I need to specify file location or something like this??
The problem is that you have writer.close(); inside the while loop. Once it's closed on the first iteration, nothing else can be written, and the exception you saw is thrown.
Place the call to close after the while loop. If you are using Java 7+, then use the "try-with-resources" syntax to have it closed when the try ends.
Why are you closing your stream right in the middle of your while loop? Rather:
while (it.hasNext()){
String line = it.next();
String entryLine = line + " -> " + dictionary.get(line);
writer.write(entryLine);
}
writer.close();
Do not close the writer in middle of while loop. Change your code as below.
private void writeToFile() {
BufferedWriter writer;
try {
String time = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
String name = "dictionaryFile" + time + ".txt";
File dictionaryFile = new File(name);
writer = new BufferedWriter(new FileWriter(dictionaryFile));
Iterator<String> it = dictionary.keySet().iterator();
while (it.hasNext()) {
String line = it.next();
String entryLine = line + " -> " + dictionary.get(line);
writer.write(entryLine);
//writer.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
writer.close();
}
}
}
Always close the IO operation in finally block, and check if instance is not null.
Related
I'm currently trying to save the output of my code into a text file, when I run it on a different project it generates the output file and stores the output respectively, however when I run the same code in a different project it gives me blank output file and I do not really know what's the matter. I'm confused as to where to put the .close() function and the flush function as well. Thank you in advance!
FileWriter output = new FileWriter("set.txt");
BufferedWriter writer = new BufferedWriter(output);
InputStream fis_n = new FileInputStream("/Users/User/NetBeansProjects/Test/src/test/sample.txt");
InputStreamReader isr_n = new InputStreamReader(fis_n, Charset.forName("UTF-8"));
BufferedReader br_n = new BufferedReader(isr_n);
while ((input = br_n.readLine()) != null) {
String[] s = input.split(":");
if (s[1].equals(text)) {
writer.write(s[0] + "'s result is " + sample_text);
writer.newLine();
break;
}
}
writer.close();
output.close();
This is what the edited code looks like, yet still the output file "set.txt" is empty upon running the program.
FileWriter output = new FileWriter("set.txt");
BufferedWriter writer = new BufferedWriter(output);
InputStream fis_n = new FileInputStream("/Users/User/NetBeansProjects/Test/src/test/sample.txt");
InputStreamReader isr_n = new InputStreamReader(fis_n, Charset.forName("UTF-8"));
BufferedReader br_n = new BufferedReader(isr_n);
try {
while ((input = br_n.readLine()) != null) {
String[] s = input.split(":");
if (s[1].equals(text)) {
writer.write(s[0] + "'s result is " + sample_text);
writer.newLine();
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
writer.close();
fis_n.close();
isr_n.close();
br_n.close();
} catch (IOException e) {
e.printStackTrace();
}
}
// fis_n.close();
//isr_n.close();
//br_n.close();
}
This is what the final code looks like:
public static void dictionary(String sample_text, String text) throws FileNotFoundException, IOException {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("/Users/User/NetBeansProjects/Test/src/test/sample.txt"),
Charset.forName("UTF-8")
));
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("/Users/User/NetBeansProjects/Test/src/test/set.txt"),
Charset.forName("UTF-8")
));
try {
String input;
while ((input = reader.readLine()) != null) {
String[] s = input.split(":");
if (s[1].equals(text)) {
writer.write(s[0] + "'s result is " + sample_text);
writer.newLine();
break;
}
}
} finally {
writer.close();
}
} finally {
reader.close();
}
} catch (IOException e) {
// Error handling
}
}
This is the main method where the dictionary method is being called.
public static void main(String[] args) throws FileNotFoundException, IOException {
case 2: {
BufferedReader d_br = new BufferedReader(new InputStreamReader(
new FileInputStream("/Users/User/NetBeansProjects/Test/src/test/input_file.txt"),
Charset.forName("UTF-8")
));
try {
String d_line;
while ((d_line = d_br.readLine()) != null) {
String h_input = test(d_line);
dictionary(d_line, h_input);
}
} catch(IOException e){
}finally {
d_br.close();
}
break;
}
}
You should put writer.close() after the while loop, and preferable, into the finally section.
If there is no requirement to store partially-processed files (as in most cases), you may remove flush at all. In the other case, it is better to leave it where it is.
The generic case of resource usage on Java 7+ looks like follows (this syntax is called try-with-resources:
try (
Resource resource1 = // Resource 1 initialization
Resource resource2 = // Resource 2 initialization
...
) {
// Resource utilization
} catch (XXXException e) {
// Something went wrong
}
Resource are freed (closed) automatically by try-with-resources.
If you need to use Java 6 or earlier, the above code could be roughly translated to the following (actually there are some subtle differences, that is not important at this level of details).
try {
Resource1 resource1 = // Resource initialization
try {
Resource2 resource2 = // Resource initialization
try {
// Resource utilization
} finally {
// Free resource2
resource2.close();
}
} finally {
// Free resource1
resource1.close();
}
} catch (XXXException e) {
// Something went wrong
}
Notice, how nested try-finally blocks used for resource management.
In your particular case we need to manage two resources: Reader and Writer, so the code will look as follows:
try (
// Notice, we build BufferedReader for the file in a single expression
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt"),
StandardCharsets.UTF_8 // Better replacement for Charset.forName("UTF-8")
));
// Alternative way to do the same
// BufferedReader reader = Files.newBufferedReader(Paths.get("sample.txt"), StandardCharsets.UTF_8);
// Output charset for writer provided explicitly
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("set.txt"),
StandardCharsets.UTF_8
))
// Alternative way to do the same
// BufferedWriter writer = Files.newBufferedWriter(Paths.get("set.txt"), StandardCharsets.UTF_8)
) {
String input;
while ((input = reader.readLine()) != null) {
String[] s = input.split(":");
if (s[1].equals(text)) {
writer.write(s[0] + "'s result is " + text);
writer.newLine();
break;
}
}
} catch (IOException e) {
// Error handling
}
Or, using pre-Java7 syntax:
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
new FileInputStream("sample.txt"),
Charset.forName("UTF-8")
));
try {
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream("set.txt"),
Charset.forName("UTF-8")
));
try {
String input;
while ((input = reader.readLine()) != null) {
String[] s = input.split(":");
if (s[1].equals(text)) {
writer.write(s[0] + "'s result is " + text);
writer.newLine();
break;
}
}
} finally {
writer.close();
}
} finally {
reader.close();
}
} catch (IOException e) {
// Error handling
}
First of all, you call the flush method of a writer, whenever you want the current buffer to be written immediately. If you just write a file completely without any intermediate operation on your output, you do not need to call it explicitly, since the close call will do that for you.
Secondly, you only call the close method of the top-level reader or writer, in your case BufferedWriter. The close call is forwarded to the other assigned readers or writers. Multiple consecutive close calls do not have any effect on a previously closed instance, see here.
As a general note to using readers and writers, consider this pattern:
// This writer must be declared before 'try' to
// be visible in the finally block
AnyWriter writer = null;
try {
// Instantiate writer here, because it can already
// throw an IOException
writer = new AnyWriter();
// The the writing in a loop or as you wish
// If you need to write out the buffer in
// between, call flush
} catch (IOException e) {
// Something went wrong while writing
} finally {
try {
if (writer != null)
writer.close();
} catch (IOException e) {
// Exception while trying to close
}
}
The finally block is ALWAYS executed. If you need a more compact syntax and you use at least Java 7, you can have a look at the try-with notation here.
While creating a method to my class, I got an unexpected problem. I've tried solutions from other theards, but they just don't work for me. My method should simply find the line specified, copy the file skipping unnecessary line, delete the original file and rename temporary file to the name of original file. It succesfuly creates new file as expected, but then fails to delete previous one as it fails to rename temporary file to original. I can't figure out, why?
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
File filePath = new File(path);
BufferedReader reader = new BufferedReader(new FileReader(file_name + ".txt"));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
filePath.delete();
temp.renameTo(theFile);
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
Try this code:
void lineDelete(String file_name, String line_to_erase){
try {
int line_number = 0;
String newline = System.getProperty("line.separator");
File temp = new File("temporary.txt");
File theFile = new File(file_name+".txt");
String path = theFile.getCanonicalPath();
BufferedReader reader = new BufferedReader(new FileReader(theFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(temp));
String lineToRemove = line_to_erase;
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)){
continue;
}
writer.write(currentLine + newline));
}
writer.close();
reader.close();
theFile.delete();
temp.renameTo(file_name + ".txt");
}
catch (FileNotFoundException e){
System.out.println(e);
}
catch (IOException e){
System.out.println(e);
}
I could suggest a couple of reasons why the delete and/or rename might fail, but there is a better way to solve your problem than guessing1.
If you use Path and the Files.delete(Path) and Files.move(Path, Path, CopyOption...) methods, they will throw exceptions if the operations fail. The exception name and message should give you clues as to what is actually going wrong.
The javadoc is here and here.
1 - Here are a couple of guesses: 1) the file has been opened elsewhere, and it is locked as a result. 2) You don't have access to delete the file.
I want to extract the first column in a file using the delimiter "," and save it into a new File.
Output generates this exception :
Exception in thread "main" java.lang.NullPointerException
at Extract.main(Extract.java:26)
Here is the code that I used butI am not sure if it is correct or not:
public class Extract {
public Extract(){
}
public static void main(String[] args) {
BufferedReader in = null;
try {
BufferedWriter out = new BufferedWriter(new FileWriter("/home/omar/Téléchargements/nursery.tmp"));
in = new BufferedReader(new FileReader("pima.txt"));
String read = null;
while ((read = in.readLine()) != null) {
read = in.readLine();
String[] splited = read.split(",");
if (splited.length > 0)
{
out.append(splited[0].toString());
out.newLine();
}
}
} catch (IOException e) {
System.out.println("There was a problem: " + e);
e.printStackTrace();
} finally {
try {
in.close();
} catch (Exception e) {
}
}
File f = new File("prima.txt");
f.delete();
File f2 = new File("pima.tmp");
f2.renameTo(new File("pima.txt"));
}
}
Remove the first line, ie read = in.readLine();, from inside your while() loop.
The problem is that you are reading the line when you are checking the while condition and inside while loop you are reading a line again (but this time a new line, because readLine not only reads a line but also moves the reading pointer to next line) so you are getting the next line.
Once you are past the end of the file you get null instead of a line, that is why you are getting Exception.
Good day! I use such part of code
File file = new File(someFilePath);
Scanner sc;
try {
sc = new Scanner(file);
} catch (FileNotFoundException e) {
return "";
}
sc.useDelimiter("\\Z");
System.out.println("file : " + file.getName() + " " + sc.hasNext() + " " + sc.delimiter());
String fileString = sc.next();
I get error Exception in thread "main" java.util.NoSuchElementException at last line of this piece of code.
And the output is file : 758279215_profile.txt false \Z, so the delimiter is correct, file exists (and it's not empty, I've checked it), but it has no next element for some reason (and as I think next element should be and it should be the whole text in the file). What's wrong and how to fix it? Thank you!
ADDED:
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while (line != null) {
try {
line = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(line);
}
returns content of a file (text file with content edited as JSON text) and null (the last itteration of the loop)
it could be locale issue.
try export LC_ALL=en_US.utf-8
I am creating an XML file from my Database and storing it in Internal storage. I require data from XML file into a single string. For which, i am using the following method.
BufferedReader br;
try {
br = new BufferedReader(new FileReader(new File(pathDAR)));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line.trim());
String temp = sb.toString().substring(38);
Log.v("XML TO String", "" + temp);
Log.v("Lengths : ", "" + temp.length() + " " + sb.length());
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I have been getting string in the Log, but it seems to be stopping abruptly in the middle.
For e.g. I am supposed to get records string like this. Beginning and ending with database tag.
<database name="DAR.db"><table name="DARWorkDetails"><row><col name="id">1</col><col name="date">05-28-2013</col><col name="visited_city_ID">1264</col><col name="employee_ID">107</col><col name="work_type_ID">1</col><col name="name">null</col><col name="customer_Id">null</col><col name="customer_type_ID">null</col><col name="sub_customer_id">null</col><col name="reason_ID">14</col><col name="reason">ABM SM MEETING</col><col name="remarks">gfhii</col><col name="work_with">211,162</col><col name="IsCustomer">N</col><col name="created_by">107</col><col name="position_id">72</col><col name="designation_Id">3</col><col name="submit_date">05-28-2013</col><col name="IsFinal">null</col></row></table></database>
Instead i have been getting string like this :
<database name="DAR.db"><table name="DARWorkDetails"><row><col name="id">1</col><col name="date">05-28-2013</col><col name="visited_city_ID">1264</col><col name="employee_ID">107</col><col name="work_type_ID">1</col><col name="name">null</col><col name="customer_Id">null</col><col name="customer_type_ID">null</col><col name="sub_customer_id">null</col><col name="reason_ID">14</col><col name="reason">ABM SM MEETING</col><col name="remarks">gfhii</col><col name="work_with">211,162</col><col name="IsCustomer">N</col><col name="created_by">107</col><col name="position_id">72</col><col name="designation_Id">3</col><col name="submit_date">05-28-2013</col><col name="IsFinal">null</co
The String is stopping in the middle. For the sake of example i have only put small example string above. In reality my database has multiple records and i have counted length of the string to around 15640, before abrupt end of the string.
Are there any limitations with StringBuilder in regards to storing characters? I suppose there is memory issue since i have been able to get string fully for records fewer than 10. Problem seems to be arising when records go into upwards of 10. Any help in understanding of solving this issue would be much appreciated.
Please check
It may happen your output is perfect but your Log cat is not displaying it whole.
Log.v("XML TO String", "" + temp);
Log.v("Lengths : ", "" + temp.length() + " " + sb.length());
See reference
I created this class to read strings from a xml file saved in internal storage device, it returns a list , if you want the whole extended string you only need concatenate to link together, if doesn't found the file return an empty list this is all you need to read XML files and parse to Strings, I hope to help!
public class readXMLFile {
private String filePath = "FileStorage";
private String fileName = "File.xml";
private final String tag = "Internal Read Persistence";
File internalFileData;
public readXMLFile() {// default constructor
}
public File getXMLFile(Context context){
File directory = null;
ContextWrapper cw = new ContextWrapper(context);
directory = cw.getDir(filePath, Context.MODE_PRIVATE);
internalFileData = new File(directory, fileName);
if(internalFileData.exists()){
Log.i("ReadXMLFile","File returned");
return internalFileData;
}
else{
Log.i(tag,"the file doesn't exists!");
return null;
}
}
public List<String> readFile(Context context) {
List<String> l = new LinkedList<String>();
try {
File directory = null;
ContextWrapper cw = new ContextWrapper(context);
directory = cw.getDir(filePath, Context.MODE_PRIVATE);
internalFileData = new File(directory, fileName);
if (internalFileData.exists()) {
Log.i("Internal Data", "the root exists!!");
try {
FileInputStream fis = new FileInputStream(internalFileData);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String line;
while ((line = br.readLine()) != null) {
l.add(line);
}
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
Log.i(tag, "Exception closing persistence connection");
}
} catch (Exception e) {
Log.wtf("Fatal Exception", "Exception: " + e.getMessage());
}
} else {
Log.i(tag, "File doesn't exists");
return l;//return empty list
}
} catch (Exception e) {
Log.wtf(tag, "Exception DATA READING: " + e.getMessage());
return l;
}
Log.i(tag, "file found return");
return l;
}
}