Closing streams using finally [closed] - java

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());
}
}

Related

Replace the first line with the longest java text file

i need to replace the first line in the text file with the longest and vice versa. Please tell me what i need to fix and add. At this stage the program looks for the longest line properly. I'm new to Java, I'm sure there is not much to fix, but I do not know what exactly is needed. Also, if possible, help implement the output of the result in a new file.
The code still looks like this:
package pkg;
import java.io.*;
import java.nio.file.Files;
import java.util.*;
public class Main {
static int previousLongLine = 0;
public void printLongLine(HashMap longLineMap) {
Set keyofSet = longLineMap.keySet();
Iterator itr = keyofSet.iterator();
while (itr.hasNext()) {
Integer keys = (Integer) itr.next();
String value = (String) longLineMap.get(keys);
System.out.println("Line Number of Longest line: " + keys
+ "\nLongest line: " + value);
}
}
public static void main(String []args){
// TODO Auto-generated method stub
String fileName = "G:\\colege\\bursa\\Colege\\Programing\\pkg\\File1.txt";
// This will reference one line at a time
String line = null;
int key = 0;
int lineSize = 0, lineNumber = 0;
Main ln = new Main();
HashMap longLineMap = new HashMap();
try {
// FileReader reads text files in the default encoding.
FileReader fileReader = new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader = new BufferedReader(fileReader);
while ((line = bufferedReader.readLine()) != null) {
lineNumber++;
lineSize = line.length();
if (lineSize > previousLongLine) {
previousLongLine = lineSize;
longLineMap.clear();
longLineMap.put(lineNumber, line);
}
if(lineNumber == 1){
String old = line;
String newl = old.replaceFirst(old, String.valueOf(previousLongLine));
}
}
//close files.
bufferedReader.close();
} catch (FileNotFoundException ex) {
System.out.println("Unable to open file '" + fileName + "'");
} catch (IOException ex) {
System.out.println("Error reading file '" + fileName + "'");
}
ln.printLongLine(longLineMap);
}
}
You can achieve this with a simple stream operation.
Info on stream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html
I've used try-with-resource, which auto-closes the resource after processing has ceased.
Info on try-with-resource: https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html
Read file into an ArrayList
Create another List to hold the sorted elements.
Open a stream on the ArrayList which holds the input data.
Sort the lines into size order. Use Comparator.reverseOrder() for largest to smallest
Using a downstream collector store the output as a new list.
Write sorted list to file.
Reading file:
String inputFile = "files/longestLine.txt";
List<String> lines = new ArrayList<>();
try(BufferedReader bufferedReader = new BufferedReader(new FileReader(inputFile))) {
String line = bufferedReader.readLine();
while(line != null){
lines.add(line);
line = bufferedReader.readLine();
}
} catch (IOException e) {
e.printStackTrace();
}
Use a stream to sort the lines into size order.
List<String> sortedLines = lines.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
Write to file:
String outputFile = "outputFile.txt";
try(BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
for (String line: sortedLines) {
bufferedWriter.write(line);
bufferedWriter.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}

Create a program that takes input from the user and writes it into the output file

This is what I have to do:
Create a new copy of the TestFileWriter program called WriterDemo that takes input from the user and writes it into the output file. The program should continue writing lines (a loop may help) until the user supplies an empty line (no text) as their input. Hint: a while loop that has a termination condition that depends on the input string from the user is a good place to start...
The program should be accessed from the terminal and I can't figure out where to put the while loop without ruining the program. The code below is the unmodified version of TestFileWriter. I don't need the full code of WriterDemo, but just some advice on how to use it. An help is greatly appreciated.
import java.io.FileReader;
import java.io.FileWriter;
public class WriterDemo {
public static void main(String args[]){;
FileWriter fout;
FileReader fin;
String str;
int k;
if(args.length==0){
System.out.println("Use an argument in the command line");
System.exit(0);
}
try{
fout = new FileWriter("WrittingProbe.txt");
for(int i=0; i<args.length; i++){
fout.write(args[i]);
fout.write(' ');
}
fout.close();
fin= new FileReader("WrittingProbe.txt");
System.out.println("The file content is:");
while((k=fin.read()) !=-1)
System.out.println((char)k);
System.out.println();
fin.close();
fout = new FileWriter("WrittingProbe.txt", true);
str="\nAdded Text\n";
fout.write(str);
fout.close();
fin = new FileReader("WrittingProbe.txt");
System.out.println("\nNow the file content is:");
while((k=fin.read()) != -1)
System.out.print((char)k);
System.out.println();
fin.close();
}
catch(Exception e){
System.out.println("Exception: " + e);
}
}
}
try (FileWriter fileWriter = new FileWriter("G:\\test.txt")) {
Scanner scn = new Scanner(System.in);
while (true) {
String string = scn.nextLine();
if (string.equals("0")) {
break;
} else {
fileWriter.write(string+"\n");
}
}
}
Scanner scn = new Scanner(System.in);
ArrayList<String> list = new ArrayList<String>();
list.add(scn.nextLine());
for(;!list.get(list.size()-1).equals("");){ //Loops until the last input is a blank line
list.add(scn.nextLine());
//Or, you can do it here, as you go, if you want
}
//Or here, all at once, using the list

Incomplete copy of a text file [duplicate]

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

How to read in information from a file, and store it as a string. Java

ive gotten this far, but this doesnt work to read in the file, thats the part im stuck on. i know that you need to use the scanner, but im not sure what im missing here. i think it needs a path to the file also, but i dont know where to put that in
public class string
{
public static String getInput(Scanner in) throws IOException
{
{
Scanner keyboard = new Scanner(System.in);
System.out.println("Enter file");
String filename =keyboard.next();
File inputFile = new File(filename);
Scanner input = new Scanner(inputFile);
String line;
while (input.hasNext())
{
line= input.nextLine();
System.out.println(line);
}
input.close();
}
if(filename.isEmpty())
{
System.out.println("Sorry, there has been an error. You must enter a string! (A string is some characters put together.) Try Again Below.");
return getInput(in);
}
else
{
return filename;
}
}
public static int getWordCount(String input)
{
String[] result = input.split(" ");
return result.length;
}
public static void main(String[] args)
{
DecimalFormat formatter = new DecimalFormat("0.##");
String input = getInput(new Scanner(System.in));
float counter = getWordCount(input);
System.out.println("The number of words in this string ("+input+") are: " + counter);
Scanner keyboard= new Scanner(System.in);
}
}
//end of code
First of all, when doing file I/O in Java, you should properly handle all exceptions and errors that can occur.
In general, you need to open streams and resources in a try block, catch all exceptions that happen in a catch block and then close all resources in a finally block. You should read up more on these here as well.
For using a Scanner object, this would look something like:
String token = null;
File file = null;
Scanner in = null;
try {
file = new File("/path/to/file.txt");
in = new Scanner(file);
while(in.hasNext()) {
token = in.next();
// ...
}
} catch (FileNotFoundException e) {
// if File with that pathname doesn't exist
e.printStackTrace();
} finally {
if(in != null) { // pay attention to NullPointerException possibility here
in.close();
}
}
You can also use a BufferedReader to read a file line by line.
BufferedReader reader = new BufferedReader(new FileReader("/path/to/file.txt"));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
With added exception handling:
String line = null;
FileReader fReader = null;
BufferedReader bReader = null;
try {
fReader = new FileReader("/path/to/file.txt");
bReader = new BufferedReader(fReader);
while ((line = bReader.readLine()) != null) {
// ...
}
} catch (FileNotFoundException e) {
// Missing file for the FileReader
e.printStackTrace();
} catch (IOException e) {
// I/O Exception for the BufferedReader
e.printStackTrace();
} finally {
if(fReader != null) { // pay attention to NullPointerException possibility here
try {
fReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bReader != null) { // pay attention to NullPointerException possibility here
try {
bReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In general, use the Scanner for parsing a file, and use the BufferedReader for reading the file line by line.
There are other more advanced ways to perform reading/writing operations in Java. Check out some of them here

Why is my program not opening my .dat file?

Hi my java program is supposed to read in and display a .txt file the user enters when prompted, convert the integers in the file to an output .dat file, then read in that .dat file and display the numbers again. When I run my program it displays the contents of the file, and creates the .dat file, but dosn't read it in again. My code is below. What do I need to do?
public class InputFile
{
public static void main(String [] args)
{
BufferedReader inputStream = null;
System.out.print("Enter file name (with .txt extension): ");
Scanner keys = new Scanner(System.in);
String inFileName = keys.next();
try
{
inputStream = new BufferedReader (new FileReader(inFileName));
System.out.println("The file " + inFileName + " contains the following lines:");
String inFileString = inputStream.readLine();
while(inFileString != null)
{
System.out.println(inFileString);
inFileString = inputStream.readLine();
}
inputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println(inFileName + " not found! Try Again.");
}
catch(IOException e)
{
System.out.println(e.getMessage());
}
String fileName = "numbers.dat";
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0);
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem opening file.");
}
catch(IOException e)
{
System.out.println("Problem with output to the file.");
}
try
{
ObjectInputStream inputStream2 = new ObjectInputStream(new FileInputStream(fileName));
System.out.println("The file being read yields:");
int anInteger = inputStream2.readInt();
while(anInteger >= 0)
{
System.out.println(anInteger);
anInteger = inputStream2.readInt();
}
inputStream2.close();
}
catch(FileNotFoundException e)
{
System.out.println("Problem with opening the file.");
}
catch(EOFException e)
{
System.out.println("Problem reading the file.");
}
catch(IOException e)
{
System.out.println("There was a problem reading the file.");
}
}
}
There's a mistype (or at least I suppose it was a mistype) hard to spot that makes your second loop infinite.
(...)
try
{
ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(fileName));
int anInt = 0;
while(anInt >=0); <=====
{
anInt = Integer.parseInt(inputStream.readLine());
outputStream.writeInt(anInt);
}
outputStream.close();
}
Remove this ';' after the while and I guess it'll run normally.
you are not writing to the output stream because by that time the inputStream has been exhausted and is closed.
create a collection to store the elements from the first file.
String inFileName = keys.next();
Collection<String> lines = new ArrayList<String>();
...
System.out.println(inFileString);
lines.add(inFileString);
...
for(String line : lines){
...
outputStream.write(Integer.parseInt(line));
...
}

Categories

Resources