Writing Out to Console as Well as to File - java

I am trying to get the output of my java program to write to a file.
The user inputs some data which should not be included in the file. When the program responds it should output information to the user, as well as write SOLELY the output to a file.
From examples I have begun with this at the top of my driver class:
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;
This code is in every place where I might receive output from the program:
try {
lineFromInput = in.readLine();
FileWrite.write(lineFromInput);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
And the class its calling is:
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
}
It creates the output file, but thats it. None of the output from the program is written.
I've looked over numerous examples and this seems to be the easiest way to get the ball rolling, although I'm open to any other suggestions.
Thanks!

Each call to write opens and closes the text file. Each time it is opened it is overwritten, so I would expect only the last thing to be written to appear in the file.
I recommend opening the output file from a constructor, and closing it from a close method.

I think it should be InputStremReader with single t in statement below:
static BufferedReader in= new BufferedReader(new OutputtStreamReader(System.in));
static String lineFromOutput;
As
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static String lineFromOutput;
EDIT: This works fine. Please make sure you provide the input through input console. Also please note that it reads and write(overwrite) single line ONLY.
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
public static void main(String[] args){
String lineFromInput;
try {
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
lineFromInput = in.readLine();
FileWrite.write(lineFromInput);
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT 2: Updated program for multi-line inputs. Its not best way to open and close file each time to write, but I am just trying to make your program work with minor changes. Let me know, if you need suggestion to avoid repeated opening/closing of the output file.
Change Highlights:
Read lines until "exit"(change the word as desired) is received in input
Open the file in append mode.
public class FileWrite {
public static void write(String message) {
PrintWriter out = null;
try {
out = new PrintWriter(new FileWriter("output.txt", true), true);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.write(message);
out.close();
}
public static void main(String[] args){
String lineFromInput = "";
try {
System.out.println("Provide the inputs in any number of lines");
System.out.println("Type \"exit\" in new line when done");
BufferedReader in = new BufferedReader(
new InputStreamReader(System.in));
while(!"exit".equals(lineFromInput)){
lineFromInput = in.readLine();
FileWrite.write(lineFromInput+System.lineSeparator());
}
in.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
EDIT3: Your updated program using Scanner to read the inputs:
private static HashMap<Integer, Object> shapes =
new HashMap<Integer, Object>();
static int i = 0;
public static void main(String[] args) {
PrintWriter output = null;
Scanner scanner = new Scanner(System.in);
try {
output = new PrintWriter(new FileWriter("output.txt"), true);
} catch (IOException e1) {
System.err.println("You don't have accress to this file");
System.exit(1);
}
String command = "";
while(!"quit".equalsIgnoreCase(command)){
System.out.println("Enter your Command: ");
command = scanner.next();
if (command.equalsIgnoreCase("create")) {
String type = scanner.next();
if (type.equalsIgnoreCase("line")) {
double length = scanner.nextDouble();
Line l = new Line(length);
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, l);
i++;
}else if (type.equalsIgnoreCase("circle")) {
double radius = scanner.nextDouble();
String color = scanner.next();
Circle c = new Circle(radius, Colors.valueOf(color));
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, c);
i++;
}else if (type.equals("rectangle")) {
double length = scanner.nextDouble();
double width = scanner.nextDouble();
String color = scanner.next();
Rectangle r = new Rectangle(length, width,
Colors.valueOf(color));
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, r);
i++;
}else if (type.equals("square")) {
double length = scanner.nextDouble();
String color = scanner.next();
Square s = new Square(length, Colors.valueOf(color));
scanner.nextLine();//flush the previous line
String line = scanner.nextLine();
output.format("%s", line);
shapes.put(i, s);
i++;
}
}else if (command.equals("printbyperimeter")) {
Shape[] shapeArray = shapes.values().toArray(new Shape[0]);
Arrays.sort(shapeArray);
System.out.println("Print in ascending order...");
for (int j = 0; j < shapeArray.length; j++) {
Shape temp = shapeArray[j];
if (temp.getClass().getName().equals("Line")) {
System.out.println("Shape: "
+ temp.getClass().getName() + ", Perimeter: "
+ temp.getPerimeter());
} else {
System.out.println("Shape: "
+ temp.getClass().getName() + ", Color: "
+ ((Colorable) temp).getColor()
+ ", Perimeter: " + temp.getPerimeter());
}
}
}else if (command.equals("printbyarea")) {
Shape[] shapeArray = shapes.values().toArray(new Shape[0]);
System.out.println("Print in random order...");
for (int j = 0; j < shapeArray.length; j++) {
Shape temp = shapeArray[j];
if (!temp.getClass().getName().equals("Line")) {
System.out.println("Shape: "
+ temp.getClass().getName() + ", Color: "
+ ((Colorable) temp).getColor() + ", Area: "
+ ((Areable) temp).getArea());
}
}
}else if (command.equals("quit")) {
scanner.close();
System.exit(0);
}
}
output.close();
}

Try using the code. It works for me. You just need to change the file path to match where you want the output to go. I am using a BufferedWriter here which I believe is preferred.
public static void main(String[] args) {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String lineFromOutput;
try {
lineFromOutput = in.readLine();
FileWrite.write(lineFromOutput);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static class FileWrite {
private static void write(String message) throws IOException {
BufferedWriter out = null;
try {
out = new BufferedWriter(new FileWriter(new File("C:\\Users\\Teresa\\Dropbox\\output.txt")));
//Replace the above line with your path.
out.write(message);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
out.close();
}
}

Related

File copier is printing out my whole excerpt, I want it to do it line by line with user input between

I need my program to print this file line by line, waiting for the user to press enter between each one. My code keeps printing the whole excerpt. What do I need to change?
import java.io.*;
import java.util.*;
public class NoteCopier {
public static void main(String[] args) throws IOException {
System.out.println("Hello! I copy an excerpt to the screen line for line"
+ " just press enter when you want a new line!");
try {
File file = new File("excerpt.txt");
FileInputStream fis = new FileInputStream(file);
InputStreamReader inreader = new InputStreamReader(fis);
BufferedReader reader = new BufferedReader(inreader);
String line = reader.readLine();
Scanner scan = new Scanner(System.in);
while(true) {
String scanString = scan.nextLine();
if(line != null) {
if(scanString.isEmpty()){
System.out.println(line);
line = reader.readLine();
}
else {
scanString = null;
break;
}
}
}
}
catch(IOException e) {
e.printStackTrace();
}
}
}
If line is null you'll loop forever; the nested if statements.
I did it in the new Stream style, without the ubiquitous but needless Scanner on System.in.
private void dump(String file) {
Path path = Paths.get(file);
BufferedReader con = new BufferedReader(new InputStreamReader(System.in));
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
System.out.println(line);
if (lineCounter.get() == 0) {
String input = null;
try {
input = con.readLine();
} catch (IOException e) {
}
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
With CtrlD you can exit on Windows I believe.
I have added that a line with a Space will dump the next 10 lines.
The ugly thing are the user input lines.
With java.io.Console one can ask input with a String prompt, which then can be used to print the file's line as prompt.
private void dump(String file) {
Path path = Paths.get(file);
Console con = System.console();
try (Stream<String> in = Files.lines(path, Charset.defaultCharset())) {
AtomicInteger lineCounter = new AtomicInteger();
in.forEach(line -> {
if (lineCounter.get() == 0) {
//String input = con.readLine("%s |", line);
String input = new String(con.readPassword("%s", line));
if (input == null) {
throw new IndexOutOfBoundsException();
} else if (input.equals(" ")) {
lineCounter.set(10);
}
} else {
System.out.println(line);
lineCounter.decrementAndGet();
}
});
} catch (IndexOutOfBoundsException e) {
System.out.println("< Stopped.");
} catch (IOException e) {
e.printStackTrace();
}
}
Using a prompt with the file's line, and asking a non-echoed "password" will be sufficient okay. You still need the Enter.
There is one problem: you must run this as real command line. The "console" in the IDE uses System.setIn which will cause a null Console. I simply create a .bat/.sh file. Otherwise System.out.print(line); System.out.flush(); might work on some operating system.

deleting a specific lines in txt file then copy to a new txt file

i am having some problem in java, i wanted to remove number 5 to number 7 and save them into a new file called RevisedNumbers.txt, is there any way to do that? this is my code so far
import java.util.Scanner;
import java.io.*;
public class Txt {
public static void main(String[] args) {
// TODO Auto-generated method stub
try {
File myObj = new File("Numbers1to10.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
Writer writer = new PrintWriter("Numbers1to10.txt");
for(int i = 1; i <= 10; i++)
{
writer.write("Number" + i);
writer.write("\r\n");
}
writer.close();
File readFile = new File("Numbers1to10.txt");
Scanner read = new Scanner(readFile);
while (read.hasNextLine())
System.out.println(read.nextLine());
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
try {
File myObj = new File("RevisedNumbers.txt");
if (myObj.createNewFile()) {
System.out.println("File created: " + myObj.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
the desired output on the new file will be
Number 1
Number 2
Number 3
Number 4
Number 8
Number 9
Number 10
One possible solution might be using an additional file.
While reading the contents of the first file ("Numbers1to10.txt"), if values are within 5 to 7, then write it into the second file ("RevisedNumbers.txt"), otherwise write it into the additional file.
Now the additional file contains values that you need in the first file. So copy all contents of the additional file into the first file.
Here is a sample code.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class FileWriteMain {
static void _write1to10(String locationWithFileName) {
try {
File file = new File(locationWithFileName);
boolean fileAlreadyExist = file.exists();
if (fileAlreadyExist) {
System.out.println("File already exists!");
} else {
System.out.println("New file has been created.");
}
FileWriter fileWriter = new FileWriter(file);
for (int i = 1; i <= 10; i++) {
fileWriter.write("Number " + i);
fileWriter.append('\n');
}
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
static File _getFile(String locationWithFileName) {
File file = null;
file = new File(locationWithFileName);
return file;
}
// it reads a file and print it's content in console
static void _readFile(Scanner scanner) {
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
System.out.println(currLine);
}
}
// read contents from sourceFile file and copy it into destinationFile
static void _copyFromOneFileToAnother(File sourceFile, File destinationFile) throws IOException {
FileWriter destFileWriter = new FileWriter(destinationFile);
Scanner scanner = new Scanner(sourceFile);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
destFileWriter.write(currLine);
destFileWriter.append('\n');
}
destFileWriter.close();
}
public static void main(String[] args) {
String locationWithFileName = "E:\\FileWriteDemo\\src\\Numbers1to10.txt"; // give your file name including it's location
_write1to10(locationWithFileName);
System.out.println("File writing done!");
File file1 = _getFile(locationWithFileName);
try {
// creating file 2
String locationWithFileName2 = "E:\\FileWriteDemo\\src\\RevisedNumbers.txt";
File file2 = _getFile(locationWithFileName2);
FileWriter fileWriter2 = new FileWriter(file2);
// creating a temporary file
String tempFileLocationWithName = "E:\\FileWriteDemo\\src\\temporary.txt";
File tempFile = _getFile(tempFileLocationWithName);
FileWriter tempFileWriter = new FileWriter(tempFile);
Scanner scanner = new Scanner(file1);
while (scanner.hasNextLine()) {
String currLine = scanner.nextLine();
// split the word "Number" from integer
String words[] = currLine.split(" ");
for (int i = 0; i < words.length; i++) {
// System.out.println(words[i]);
try {
int num = Integer.parseInt(words[i]);
if (num >= 5 && num <= 7) {
// writing to second file
fileWriter2.write(currLine);
fileWriter2.append('\n');
} else {
// writing to temporary file
tempFileWriter.write(currLine);
tempFileWriter.append('\n');
}
} catch (NumberFormatException e) {
// current word is not an integer, so don't have to do anything
}
}
}
fileWriter2.close();
tempFileWriter.close();
_copyFromOneFileToAnother(tempFile, file1);
System.out.println("\nContents of first file");
_readFile(new Scanner(file1));
System.out.println("\nContents of second file");
_readFile(new Scanner(file2));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Hope it helps!
Happy coding.

how to copy only a part of .CSV based on first column elements with java

copy part like this(from date to date) I am trying to copy only a part of .CSV file based on the first column (Start Date and Time) data looks like (2019-01-28 10:22:00 AM) but the user have to put it like this (2019/01/28 10:22:00)
this is for windows, java opencsv , this is what I found but dont do what I need exaclty :
like this:
int startLine = get value1 from column csv ;
int endLine = get value2 from column csv;
public static void showLines(String fileName, int startLine, int endLine) throws IOException {
String line = null;
int currentLineNo = 1;
// int startLine = 20056;//40930;
// int currentLineNo = 0;
File currentDirectory = new File(new File(".").getAbsolutePath());
String fromPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
PrintWriter pw = null;
pw = new PrintWriter(new FileOutputStream(fromPath), true);
//pw.close();
BufferedReader in = null;
try {
in = new BufferedReader (new FileReader(fileName));
//read to startLine
while(currentLineNo<startLine) {
if (in.readLine()==null) {
// oops, early end of file
throw new IOException("File too small");
}
currentLineNo++;
}
//read until endLine
while(currentLineNo<=endLine) {
line = in.readLine();
if (line==null) {
// here, we'll forgive a short file
// note finally still cleans up
return;
}
System.out.println(line);
currentLineNo++;
pw.println(line);
}
} catch (IOException ex) {
System.out.println("Problem reading file.\n" + ex.getMessage());
}finally {
try { if (in!=null) in.close();
pw.close();
} catch(IOException ignore) {}
}
}
public static void main(String[] args) throws FileNotFoundException {
int startLine = 17 ;
int endLine = 2222;
File currentDirectory = new File(new File(".").getAbsolutePath());
try {
showLines(currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv", startLine, endLine);
} catch (IOException e) {
e.printStackTrace();
}
// pw.println();
}
Common CSV format uses a comma as a delimiter, with quotations used to escape any column entry that uses them within the data. Assuming that your column one data is consistent with the format you posted, and that I wouldn't have to bother with quotations marks therefor, you could read the columns as:
public static void main(String[] args) {
//This is the path to the file you are writing to
String targetPath = "";
//This is the path to the file you are reading from
String inputFilePath = "";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/01/28 10:30:00";
String addFlagSplit[] = startLine.replace("/", "-").split(" ");
String addFlag = addFlagSplit[0] + " " + addFlagSplit[1];
String endFlagSplit[] = endLine.replace("/", "-").split(" ");
String endFlag = endFlagSplit[0] + " " + endFlagSplit[1];
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(addFlag)) {
add = true;
}else if(date.contains(endFlag)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
File currentDirectory = new File(new File(".").getAbsolutePath());
String targetPath = currentDirectory.getCanonicalPath() + "\\Target\\part.csv";
String inputFilePath = currentDirectory.getCanonicalPath() + "\\Sources\\concat.csv";
String line = null;
ArrayList<String> lines = new ArrayList<String>();
boolean add = false;
String startLine = "2019/01/28 10:22:00";
String endLine = "2019/04/06 10:30:00";
try(PrintWriter pw = new PrintWriter(new FileOutputStream(targetPath), true)){
try (BufferedReader input = new BufferedReader(new FileReader(inputFilePath))){
while((line = input.readLine()) != null) {
String date = line.split(",")[0];
if(date.contains(startLine)) {
add = true;
}else if(date.contains(endLine)) {
break;
}
if(add) {
lines.add(line);
}
}
}
for(String currentLine : lines) {
pw.append(currentLine + "\n");
}
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {
e.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}
}

Java - Problems with returning an integer array

I'm trying to read a .txt file called Heights.txt, which contains a string of numbers, each separated by a ":". The method produces one error that I can't seem to figure out.
It says that "the method must return a result of type int[]", at the very first line of this code.
I don't understand why it says this, as integerHeightDataPoints should be an integer array at that point, and should be able to be returned to a int[] method?
public static int[] readFile(){
BufferedReader br = null;
String dataPoints;
try {
br = new BufferedReader(new FileReader("Path\\Heights.txt"));
}
catch(IOException e) {
System.out.println("Please enter data first");
System.exit(0);
}
try {
while((dataPoints = br.readLine()) != null) {
if (dataPoints.contains(":")) {
String[] heightDataPoints = dataPoints.split(":");
int[] integerHeightDataPoints = new int[heightDataPoints.length];
for (int i = 0; i < integerHeightDataPoints.length; i++) {
integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
}
return integerHeightDataPoints;
}
}
}
catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
}
It's because you don't return anything in second IOException case or (as #Exception_al mentioned) when while never triggers.
public static int[] readFile() {
BufferedReader br = null;
String dataPoints;
try {
br = new BufferedReader(new FileReader("/tmp/file1"));
} catch (IOException e) {
System.out.println("Please enter data first");
System.exit(0);
}
int[] integerHeightDataPoints = new int[0];
try {
while ((dataPoints = br.readLine()) != null) {
if (dataPoints.contains(":")) {
String[] heightDataPoints = dataPoints.split(":");
integerHeightDataPoints = new int[heightDataPoints.length];
for (int i = 0; i < integerHeightDataPoints.length; i++) {
integerHeightDataPoints[i] = Integer.parseInt(heightDataPoints[i]);
}
return integerHeightDataPoints;
}
}
} catch (IOException e) {
System.out.println("Error reading file");
e.printStackTrace();
}
return integerHeightDataPoints;
}

Create multiple files from one text file in java

I have one input.txt file which consist on let suppose 520 lines.
I have to make a code in java which will act like this.
Create first file named file-001.txt from first 200 lines. then create another file-002 from 201-400 lines. then file-003.txt from remaining lines.
I have coded this, it just write first 200 lines. What changes I need to make in order to update its working to above scenario.
public class DataMaker {
public static void main(String args[]) throws IOException{
DataMaker dm=new DataMaker();
String file= "D:\\input.txt";
int roll=1;
String rollnum ="file-00"+roll;
String outputfilename="D:\\output\\"+rollnum+".txt";
String urduwords;
String path;
ArrayList<String> where = new ArrayList<String>();
int temp=0;
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
for(String line; (line = br.readLine()) != null; ) {
++temp;
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
}
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
void filewriter(String linetoline,String filename) throws IOException{
BufferedWriter fbw =null;
try{
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(filename, true), "UTF-8");
fbw = new BufferedWriter(writer);
fbw.write(linetoline);
fbw.newLine();
}catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}
finally {
fbw.close();
}
}
}
One way can be use of if else but I cant just use it because my actual file is 6000+ lines.
I want this code to work like I run the code and give me 30+ output files.
You can change the following bit:
if(temp<201){ //may be i need some changes here
dm.filewriter(line+" "+temp+")",outputfilename);
}
to this:
dm.filewriter(line, "D:\\output\\file-00" + ((temp/200)+1) + ".txt");
This will make sure first 200 lines go to first file, next 200 lines go to next file and so on.
Also, you might want to batch 200 lines together and write them in one go rather than creating a writer everytime and write to file.
You may have a method that creates the Writer to the current File, reads up to limit number of lines, closes the Writer to the current File, then returns true if it had enough to read , false if it couldn't read the limit number of lines (i.e, abort next call, don't attempt to read more lines or write next file).
Then you would call this in a loop , passing the Reader, the new file name, and the limit number.
Here is an example :
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
public class DataMaker {
public static void main(final String args[]) throws IOException {
DataMaker dm = new DataMaker();
String file = "D:\\input.txt";
int roll = 1;
String rollnum = null;
String outputfilename = null;
boolean shouldContinue = false;
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
do {
rollnum = "file-00" + roll;
outputfilename = "D:\\output\\" + rollnum + ".txt";
shouldContinue = dm.fillFile(outputfilename, br, 200);
roll++;
} while (shouldContinue);
} catch (FileNotFoundException e) {
System.out.println("File not found");
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private boolean fillFile(final String outputfilename, final BufferedReader reader, final int limit)
throws IOException {
boolean result = false;
String line = null;
BufferedWriter fbw = null;
int temp = 0;
try {
OutputStreamWriter writer = new OutputStreamWriter(
new FileOutputStream(outputfilename, true), "UTF-8");
fbw = new BufferedWriter(writer);
while (temp < limit && ((line = reader.readLine()) != null)) {
temp++;
fbw.write(line);
fbw.newLine();
}
// abort if we didn't manage to read the "limit" number of lines
result = (temp == limit);
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
} finally {
fbw.close();
}
return result;
}
}

Categories