Incomplete copy of a text file [duplicate] - java

This question already has answers here:
BufferedWriter not writing everything to its output file
(8 answers)
Closed 8 years ago.
This is my input file:
This is a file test.
please take
notice of it.
Peace.
and this is the output:
This is a file test.
please take
notice of
I do not understant why it stops and "it." ,but it displays the word "test.".
Here's the code:
import java.io.*;
import java.util.*;
public class FileTest {
public static void readFile() throws Throwable {
File _output = new File("output.txt");
FileWriter _filewr = new FileWriter(_output);
BufferedWriter _buffwrt = new BufferedWriter(_filewr);
FileInputStream f = new FileInputStream(
"C:\\Users\\Diana\\Desktop\\FileTest\\test.txt.txt");
BufferedReader _buffer = new BufferedReader(new InputStreamReader(f));
String _str = _buffer.readLine();
while (_str != null) {
String[] _vect = _str.split(" ");
int i;
for (i = 0; i < _vect.length; i++) {
if (_vect[i].contains(".")) {
_buffwrt.write(_vect[i] + " ");
break;
}
else
_buffwrt.write(_vect[i] + " ");
_buffwrt.flush();
}
_str = _buffer.readLine();
}
}
public static void main(String[] args) throws Throwable {
readFile();
}
}

use another _buffwrt.flush(); outside the loop to flush anything remaining and don't forget _buffwrt.close(); at the end
update
#Svetlin Zarev mention a good point that only _buffwrt.close(); at the end will be sufficient to flush anything remaining
http://docs.oracle.com/javase/7/docs/api/java/io/BufferedWriter.html#close%28%29

The basic answer is, the break statement is breaking out of the loop, which is what you want, but it's also skipping the _buffwrt.flush(); statement. Because you're not closing the output streams correctly, the buffered content is simply been discard.
While you could put more flush statements in, it kind of defeats the purpose of BufferedWriter, instead, you should simply manage you resources better and make sure that they are getting closed when you are done with them, which will, in this case, flush the buffers before closing the resource.
File _output = new File("output.txt");
try (BufferedWriter _buffwrt = new BufferedWriter(new FileWriter(_output))) {
try (BufferedReader _buffer = new BufferedReader(new FileReader("test.txt"))) {
String _str = _buffer.readLine();
while (_str != null) {
String[] _vect = _str.split(" ");
int i;
for (i = 0; i < _vect.length; i++) {
if (_vect[i].contains(".")) {
System.out.println("1 " + _vect[i]);
_buffwrt.write(_vect[i] + " ");
break;
} else {
System.out.println("2 " + _vect[i]);
_buffwrt.write(_vect[i] + " ");
}
}
_str = _buffer.readLine();
}
}
} catch (IOException exp) {
exp.printStackTrace();
}
Take a look at The try-with-resources Statement for more details

Related

Closing streams using finally [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm new to Java and just learned I should close streams in a try/catch/finally block but it's forcing me to use another try-catch inside the finally wrap, otherwise I have to throw an Exception.
This code is from an exercise and I'm trying not only to pass it but to establish good coding practices. Could you please have at my closing approach? Feel free to criticise other aspects of the code and tear it apart. That's the only way I'll get better.
/*
Read 2 file names from the console: file1, file2.
Write all the bytes in file1 to file2, but in the reverse order.
Close the streams.
Requirements:
1. The program should read a file name twice from the console.
2. Use FileInputStream to read from a file, and use FileOutputStream to write to a file.
3. In the second file, you need to write all the bytes from the first file in the reverse order.
4. The FileInputStream and FileOutputStream must be closed.
*/
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
public class Solution {
private void copyArray () {
FileInputStream input = null;
FileOutputStream output = null;
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter a filename to be read: ");
String file1 = reader.readLine();
System.out.print("Enter a filename to write to: ");
String file2 = reader.readLine();
input = new FileInputStream(file1);
output = new FileOutputStream(file2);
byte[] buffer = new byte[input.available()];
int count = input.available();
input.read(buffer);
for (int i = count-1; i>=0; i--) {
output.write(buffer[i]);
}
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
} finally {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
new Solution().copyArray();
}
}
you can use try with resources
try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))){
System.out.print("Enter a filename to be read: ");
String file1 = reader.readLine();
System.out.print("Enter a filename to write to: ");
String file2 = reader.readLine();
try(FileInputStream input = new FileInputStream(file1);FileOutputStream output = new FileOutputStream(file2)){
byte[] buffer = new byte[input.available()];
int count = input.available();
input.read(buffer);
for (int i = count-1; i>=0; i--) {
output.write(buffer[i]);
}
}
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
}
Please go through guidelines before posting any question.
Anyways, I believe, this would be correct way to use Java feature - Try with Resource
private static void copyArray () {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a filename to be read: ");
String file1 = scanner.next();
System.out.print("Enter a filename to write to: ");
String file2 = scanner.next();
scanner.close();
try (FileInputStream input = new FileInputStream(new File(file1)) ;
FileOutputStream output = new FileOutputStream(new File(file2))){
byte[] buffer = new byte[input.available()];
int count = input.available();
input.read(buffer);
for (int i = count-1; i>=0; i--) {
output.write(buffer[i]);
}
} catch (IOException e) {
System.out.println("General I/O exception: " + e.getMessage());
}
}

Changing the first line in a file

I'm having an issue with changing a line in a file, the purpose of this code is to change the first number of the file to itself + 1. For some reason the code doesn't seem to be functioning at all, any help would be appreciated!
public static void changenumber(String fileName)
{
ArrayList<String> list = new ArrayList<String>();
File temp = new File(fileName);
Scanner sc;
try {
sc = new Scanner(temp);
while (sc.hasNextLine())
{
list.add(sc.nextLine());
}
sc.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
String first = list.get(0);
int i = Integer.parseInt(first);
i = i+1;
first = Integer.toString(i);
list.set(0, first);
writenumber(list,fileName);
}
public static void writenumber(ArrayList<String> list, String fileName)
{
PrintWriter write;
try {
write = new PrintWriter(new FileWriter(fileName, true));
for(int i = 0; i<list.size();i++)
{
write.append(list.get(i));
}
}
catch(IOException err)
{
err.printStackTrace();
}
}
Your problem is that you never closed the FileWriter.
Use try-with-resources to ensure that file streams are closed correctly.
A few other improvements to your code:
Do not ignore exceptions. Continuing execution as-if nothing bad happened will cause lots of problems. Let the exception bounce back to caller, and let caller decide what to do if the file cannot be updated.
Scanner is slow. Since all you're doing to reading lines, use BufferedReader instead.
The lines in memory don't end in newline characters, so you need to use the println() method when writing the lines back out, otherwise the result is a file with all the lines concatenated into a single line.
Variables renamed to be more descriptive.
public static void changenumber(String fileName) throws IOException {
ArrayList<String> lines = new ArrayList<>();
try (BufferedReader in = new BufferedReader(new FileReader(fileName))) {
for (String line; (line = in.readLine()) != null; ) {
lines.add(line);
}
}
int i = Integer.parseInt(lines.get(0));
i++;
lines.set(0, Integer.toString(i));
writenumber(lines, fileName);
}
public static void writenumber(List<String> lines, String fileName) throws IOException {
try (PrintWriter out = new PrintWriter(new FileWriter(fileName, true))) {
for (String line : lines) {
out.println(line);
}
}
}
Of course, you could simplify the code immensely by using the newer NIO.2 classes added in Java 7, in particular the java.nio.file.Files class.
public static void changenumber(String fileName) throws IOException {
Path filePath = Paths.get(fileName);
List<String> lines = Files.readAllLines(filePath);
lines.set(0, Integer.toString(Integer.parseInt(lines.get(0)) + 1));
Files.write(filePath, lines);
}

program that uses input file and creates a new one

I'm writing a code that uses an input file called InvetoryReport.txt in a program I am supposed to create that is supposed to take this file, and then multiply two pieces of data within the file and then create a new file with this data. Also at the beginning of the program it is supposed to ask you for the name of the input file. You get three chances then it is to inform you that it cannot find it and will now exit, then stop executing.
My input file is this
Bill 40.95 10
Hammer 1.99 6
Screw 2.88 2
Milk .03 988
(The program is supposed to multiply the two numbers in the column and create a new column with the sum, and then under print another line like this
" Inventory Report
Bill 40.95 10 409.5
Hammer 1.99 6 11.94
Screw 2.88 2 5.76
Milk .03 988 29.64
Total INVENTORY value $ 456.84"
and my program I have so far is this
package textfiles;
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.IOException;
public class LookOut{
double total = 0.0;
String getFileName(){
System.out.printIn("Type in file name here.");
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
out.println(str + "\n");
}
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
return str;
}
void updateTotal(double d){
total = total + d;
}
double getLineNumber(int String_line){
String [] invRep = line.split(" ");
Double x = double.parseDouble(invRep[1]);
Double y = double.parseDouble(invRep[2]);
return x * y;
}
void printNewData(String = newData) {
PrintWriter pW = new PrintWriter ("newData");
pw.print(newData);
pw.close;
}
public static void main(String[] args){
String str = ("Get file name");
String str = NewData("InventoryReport/n");
File file = new File(str);
Scanner s = new Scanner(file);
while(s.hasNextLine()) {
String line = s.nextLine();
double data = getLineNumber(line);
update total(data);
NewData += line + " " + data + "/n";
Print NewData(NewData);
}
}
}
I'm getting multiple error codes that I just cant seem to figure out.
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
} catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Despite your best intentions you are in fact missing a '}'. Note that you haven't escaped the Try block before the catch. I imagine this is because you confused the closing } for the while statement as the closing } for the try block. Do this instead:
try {
int count =1;
FileReader fr = new FileReader("InventoryReport.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while ((str = br.readLine()) != null) {
br.close();
}
}
catch (IOException e) {
if(count == 3) {
System.out.printIn("The program will now stop executing.");
System.exit(0);
count++;
}
}
Also, your indentation is ALL OVER THE PLACE. This should be a lesson to you in why you should format your code properly! It is so easy to miss simple syntax errors like that if you're not formatting properly. It's also hard for others to read your code and figure out what's wrong with it.

Writing and reading int from file after loop

I'm writing an application that is supposed to act like a cafe clip card. In other words, for every n:th (10 in my case) coffee that a customer purchases, he/she is awarded a free beverage. So, I'm quite done with the loop and I've been working on writing and reading from a file since I need the program to remember where it last left off in order for the customer to be able to close the application once he/she has been in the store. However, I'm having a difficult time figuring out how to write and read from a file, the code I have doesn't seem to output any .txt file. I need the code to have a closing condition, and upon entering this condition, it should write the "count" to a .txt file, and shut down. Once the program is being run the next time it should read from this .txt file so it knows where the count is at.
Here's what I have so far:
public class FelixNeww {
public static void main(String [] args) {
Scanner key;
String entry;
int count = 0;
String password = "knusan01";
while(true) {
System.out.println("Enter password: ");
key = new Scanner(System.in);
entry = key.nextLine();
if(entry.compareTo(password) == 0){
count++;
System.out.println("You're one step closer to a free coffe! You have so far bought "
+ count + " coffe(s)");
}
if(count == 10 && count != 0){
System.out.println("YOU'VE GOT A FREE COFFE!");
count = 0;
}
if(entry.compareTo(password) != 0){
System.out.println("Wrong password! Try again.\n");
}
}
}
public void saveToFile(int count)
{
BufferedWriter bw = null;
try
{
bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File("countStorage.txt"))));
bw.write(count);
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(bw != null)
{
try
{
bw.close();
}
catch(IOException e) {}
}
}
}
public int readFromFile()
{
BufferedReader br = null;
try
{
br = new BufferedReader(newInputStreamReader(newFileInputStream(new File("countStorage.txt"))));
String line = br.readLine();
int count = Integer.parseInt(line);
return count;
}
catch(IOException e)
{
e.printStackTrace();
}
finally
{
if(br != null)
{
try
{
br.close();
}
catch(IOException e) {}
}
}
return 0;
}
}
I see a few problems here. In your readFromFile() method, put a space after the keyword new. I also suggest putting a an absolute path for now (for debugging):
br = new BufferedReader(new InputStreamReader(new FileInputStream(new File("C:\\Temp\\countStorage.txt"))));
In your saveToFile() method, the constructor is wrong. Also put the full path to the file here:
bw = new BufferedWriter(new FileWriter("C:\\Temp\\countStorage.txt"));
Finally, in your saveToFile() method, write the count as a String. Writing it as an int refers to the Unicode character:
bw.write(Integer.toString(count)); //updated per Hunter McMillen
And invoke it...
FelixNeww f = new FelixNeww();
f.saveToFile(44);
System.out.println(f.readFromFile());
You need to invoke readFromFile or saveToFile in the place needed in order to become executed.
I suggest that you call readFromFile on the beginning of the Main method, use its returning contents, and saveToFile in the loop whenever the desired state changes and it needs to be saved.

Multiple 'if' statements into one outputStream

import java.io.*;
import java.io.File;
import java.io.FilenameFilter;
public class YDSearch{
public void listFiles(String dir) throws IOException{
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .mp3 return true, else false
return name.endsWith(".mp3")||name.endsWith(".mp4")||name.endsWith(".3gp")
||name.endsWith(".mov")||name.endsWith(".avi")||name.endsWith(".wmv");
}
};
String[] filenames = directory.list(filefilter);
DataOutputStream output = new DataOutputStream(new FileOutputStream("C:/Users/Jonathan/Desktop/YouDetect/SearchByFileType/AllMediaFiles.dat"));
for (String name : filenames) {
output.writeUTF(dir + name);
}
output.close();
DataInputStream input = new DataInputStream(new FileInputStream("C:/Users/Jonathan/Desktop/YouDetect/SearchByFileType/AllMediaFiles.dat"));
DataOutputStream output2 = new DataOutputStream(new FileOutputStream("C:/Users/Jonathan/Desktop/ReadyForAnalysis.dat"));
for (String name : filenames) {
FileInputStream in = new FileInputStream(input.readUTF());
int byteCounter = 0;
int rowCounter = 0;
long bufferCounter = 0;
if(name.endsWith(".mp3")){
byte[] b = new byte[36];
int read = in.read(b, 0, 36);
if (byteCounter != 1000){
if (rowCounter == 1){
System.out.println("\n");
rowCounter = 0;
}
output2.writeUTF(org.apache.commons.codec.binary.Hex.encodeHexString(b)+ " " + dir + name);
bufferCounter ++;
rowCounter ++;
}else{
byteCounter = 0;
try{
Thread.sleep(200);
}catch(InterruptedException e) {
}
}
}
else if(name.endsWith(".mp4")){
byte[] b = new byte[29];
int read = in.read(b, 0, 29);
if (byteCounter != 1000){
if (rowCounter == 1){
System.out.println("\n");
rowCounter = 0;
}
output2.writeUTF(org.apache.commons.codec.binary.Hex.encodeHexString(b)+ " " + dir + name);
bufferCounter ++;
rowCounter ++;
}else{
byteCounter = 0;
try{
Thread.sleep(200);
}catch(InterruptedException e) {
}
}
}
//System.out.println("====================");
}
output2.close();
input.close();
DataInputStream input2 = new DataInputStream(new FileInputStream("C:/Users/Jonathan/Desktop/ReadyForAnalysis.dat"));
for (String name : filenames) {
System.out.println(input2.readUTF()+"\n");
}
}
public void checkHeaderSC(String allFiles)throws IOException{
}
public static void main(String[] args) throws IOException {
YDSearch YDSearch = new YDSearch();
YDSearch.listFiles("C:/Users/Jonathan/Desktop/YD Tests/1) High Quality/");
YDSearch.listFiles("C:/Users/Jonathan/Desktop/YD Tests/2) Medium Quality/");
YDSearch.listFiles("C:/Users/Jonathan/Desktop/YD Tests/3) Low Quality/");
YDSearch.checkHeaderSC("C:/Users/Jonathan/Desktop/YouDetect/SearchByFileType/ReadyForAnalysis.dat");
}
}
Hey there, having a little issue with the above coding and hoped someone here might be able to help. This is sort of a partial version of the code as the real one has 4 more if/else if statements involved.
The program compiles and begins to run fine. It produces several results back from the file that is being read into/then out of again in input2 but then stops, produces no more results and gives the error:
Exception in thread "main" java.io.EOFException
at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:323)
at java.io.DataInputStream.readUTF(DataInputStream.java:572)
at java.io.DataInputStream.readUTF(DataInputStream.java:547)
at YDSearch.listFiles(YDSearch.java:85)
at YDSearch.main(YDSearch.java:93)
Anybody know why this might be happening and have a solution they could share?
I've also tried making the variable 'b' to be inside of an if statement but that doesn't work because of scope. If b was defined by if's then there would only need to be one if statement to output to the file
Please let me know if you've got any ideas, I'd really appreciate it :)
As far as I can see, you don't always put out an output record for every name, only for when the name matches one of your patterns. However, you do try to read an input record for every name.
Ergo, if you have any filenames that don't match the patterns you try to read more than you write, and you will get the EOF.
EDIT:
In more detail, the problem is that you get a list of all the files that end with "mp3", "mp4", "3gp", "mov", "avi or "wmv". You then process that list, and write out something into C:/Users/Jonathan/Desktop/ReadyForAnalysis.dat for each "mp3" and "mp4" file. You then assume that for each entry in your list of files, that you will have an entry in ReadyForAnalysis.dat. However, if there are any files ending in "3gp", "mov", "avi or "wmv" then this will not hold true.

Categories

Resources