Writing from file to file program - java

I'm trying to make a program that reads a line from the database.txt and writes an odd/even numbered lines to files 1.txt and 2.txt. F.e. 1st(odd) line of the database.txt goes to 1.txt and the 2nd(even) line of the database.txt goes goes to 2.txt
Here's the code I got so far:
import java.io.*;
import java.util.Scanner;
public class Main {
public Main(){
op(null);
}
public void op(String args[]){
try{
FileReader fr = new FileReader("database.txt");
BufferedReader reader = new BufferedReader(fr);
String line = reader.readLine();
Scanner scan = null;
int ln = 1;
String even = "2txt";
String odd = "1.txt";
while ((line=reader.readLine())!=null){
scan = new Scanner(line);
if(ln%2==0){
wtf(even, line);
}else{
wtf(odd, line);
}
ln++;
line=reader.readLine();
}
reader.close();
}
catch (FileNotFoundException e){
System.out.println("File not found");
}
catch (IOException e) {
System.out.println("Impossibru to read");
}
}
public void wtf(String filename, String ltw){
try
{
FileReader fr = new FileReader(filename);
BufferedReader reader = new BufferedReader(fr);
String line = reader.readLine();
FileWriter writer = new FileWriter(filename);
BufferedWriter bw = new BufferedWriter(writer);
while(line==null){
bw.write(ltw);
bw.newLine();
}
bw.close();
}
catch ( IOException e)
{
}
}
}
At the moment its on an infinite loop reads only the 2nd line and spams it to 1.txt

Within the:
if(ln%2==0)
block you also need to add ln++;
Also move the
line=reader.readLine();
to directly outside the else block.
As an alternative, this is a somewhat reworked method:
Remove all of the line=reader.readLine();s including the first.
Rewrite the loop as:
while ((line=reader.readLine())!=null){
if(ln%2==0){
wtf(even, line);
}else{
wtf(odd, line);
}
ln++;
}

You are not incrementing the line count.
while (line!=null){
scan = new Scanner(line);
if(ln%2==0){
wtf(even, line);
ln++;
}else{
wtf(odd, line);
ln++;
line=reader.readLine();
}
}
reader.close();
}

if(ln%2==0){
wtf(even, line);
}else{
wtf(odd, line);
} //<------------here ?
ln++;
line=reader.readLine();
// }
}
reader.close();
update:
while((line=reader.readLine())!=null){
*
*
*
line=reader.readLine() ; //is this line required ?
update:
Check this also in wtf()
while(line==null){
bw.write(ltw);
bw.newLine();
}

The problem was with the wtf method. Your endless loop was in there when you wrote:
while(line==null){
bw.write(ltw);
bw.newLine();
}
BufferedReader states it returns null if the end of the stream has been reached. Since your files are initially empty (I'm assuming), this will constantly be true, and you will continue writing new lines and your String.
I was playing around with your code and rewrote it to something like this.
import java.util.*;
import java.io.*;
public class fread {
public static void main (String[] args) {
Scanner scan = new Scanner(System.in);
String even = "2.txt";
String odd = "1.txt";
String line = "";
int lineNumber = 0;
while (scan.hasNext() )
{
line = scan.nextLine();
if (lineNumber++ % 2 == 1)
writeText(even, line);
else
writeText(odd, line);
}
}
static void writeText(String filename, String ltw)
{
try
{
BufferedWriter bw = new BufferedWriter(new FileWriter(filename, true));
bw.write(ltw);
bw.newLine();
bw.close();
}
catch ( IOException e)
{
e.printStackTrace();
}
}
}
It uses input redirection, so typing java fread < database.txt will give you your results, however this only does appends to a file. If your files do not exist, or are initially empty, this will work as you expect. You'll have to specify this code to the needs of the program. Regardless, you should be able to take my writeText method and incorporate it into your program to be able to to get yours working.

Your infinite loop is happening here:
if(ln%2==0)
wtf(even, line);
ln starts at 0. 0 % X = 0, therefore it is always considered an even number, and you just keep spamming out to the same line. Add the increment to your even clause.
Interesting side note
You have another infinite loop, because if the value is even, or 0, then you never read the next line.
Solution
if(ln%2==0){
wtf(even, line);
ln ++;
line = reader.readline();

Related

Is Eclipse not accepting Enter/Return as a null character now?

I have made the following simple program that changes normal quotes to TEX quotes
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class TexQuotes {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
PrintWriter pw = new PrintWriter(System.out);
String lines;
boolean first = true;
while ((lines = br.readLine()) != null) {
for (char c: lines.toCharArray())
if (c == '"') {
pw.print(first ? "``" : "''");
first = !first;
}
else pw.print(c);
pw.println();
}
br.close();
pw.flush();
}
}
The problem is that when trying to input something in the Eclipse console and pressing enter, nothing is output back. The code worked fine on an old version of Eclipse, but is Eclipse now not accepting the Enter as a null indicator?
Note: Also, sometimes when pressing Ctrl+Z I get an output, but most often it too does not work. Any other Ctrl + key combination does not work.
Edit: For example, when I enter the following statement as input:
"So there are seven now", said John, "and we need to figure out which one."
I expect the output:
``So there are seven now'', said John, ``and we need to figure out which one.''
The problem is that I never exit out of the while loop and so the output is never flushed, because the while loop accepts input until a null character is input. The problem is of course, I don't know how a null character is input in Eclipse.
import java.util.Scanner;
public class TexQuotes {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
String line;
while (stdin.hasNextLine()) {
line = stdin.nextLine();
boolean start = true;
while (line.indexOf('"') >= 0) {
if (start) {
line = line.replaceFirst("\"", "``");
start = false;
}
else {
line = line.replaceFirst("\"", "''");
start = true;
}
}
System.out.println(line);
}
System.out.println(" *** TexQuotes.main() completed ***");
}
}
You terminate the while loop by entering end of file, i.e. Ctrl+Z on Windows, by itself.
Until you enter end of file, you enter a line of text and then press ENTER key.
After pressing ENTER key, all double quote characters in the entered text are replaced alternately by your tex quotes.
EDIT
Using BufferedReader and PrintWriter...
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
PrintWriter pw = new PrintWriter(System.out);
try {
String line = br.readLine();
while (line != null) {
boolean start = true;
while (line.indexOf('"') >= 0) {
if (start) {
line = line.replaceFirst("\"", "``");
start = false;
}
else {
line = line.replaceFirst("\"", "''");
start = true;
}
}
pw.println(line);
pw.flush();
line = br.readLine();
}
}
catch (IOException xIo) {
xIo.printStackTrace();
}

Write to a specific line in a txt document java

I know that there are already some posts about this problem but I don't understand them.
My problem is that I want to find a line in a txt document with a name and I then want to change the next line to the content of a string.
This is what I tried:
public void saveDocument(String name) {
String documentToSave = textArea1.getText();
File file = new File("documents.txt");
Scanner scanner;
BufferedWriter bw;
try {
scanner = new Scanner(file);
bw = new BufferedWriter(new FileWriter(file));
while(scanner.hasNextLine()) {
if(scanner.nextLine().equals(name)) {
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
bw.write(documentToSave + "\n");
if(scanner.hasNextLine()) scanner.nextLine();
}
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
May be you try it this way: read your file and keep each line in a list of strings and if you find the name you are looking for replace the next line you read. And then write the strings from that list back to your file. Example:
public class NewClass {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list = readFile("uzochi");
writeToFile(list);
}
public static List<String> readFile(String name){
List<String> list = new ArrayList<String>();
try {
FileReader reader = new FileReader("C:\\users\\uzochi\\desktop\\txt.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
boolean nameFound = false;
while ((line = bufferedReader.readLine()) != null) {
if(line.equalsIgnoreCase(name)){
nameFound = true;
System.out.println("searched name: "+line);
}
if(nameFound){
list.add(line);
line = bufferedReader.readLine();
System.out.println("line to replace: " + line);
line = "another string";
System.out.println("replaced line: "+line);
list.add(line);
nameFound = false;
}
else{
list.add(line);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void writeToFile(List<String> list){
try {
FileWriter writer = new FileWriter("C:\\users\\uzochi\\desktop\\txt.txt", false);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(String s: list){
bufferedWriter.write(s);
bufferedWriter.newLine();
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
txt.txt
hallo
hello
hola
uzochi
world
java
print
This code should read the entire file and replace the line with the name.
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.equals(name)) {
bw.write(documentToSave + "\n");
} else {
bw.write(line + "\n");
}
}
This program will replace the line after a given line. It needs some more work from us, for example if we can define expected i/o and usage. Now it reads from a file and reeplaces a line, but maybe you want to use the line number instead of the line contents to mark which line to replace.
import java.io.*;
public class FileLineReplace {
public static void replaceSelected(String replaceWith, String type) {
try {
String input2 = "";
boolean replace = false;
String input = "";
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
for (String line;
(line = br.readLine()) != null;) {
// process the line.
System.out.println(line); // check that it's inputted right
if (replace) {
line = "*** REPLACED ***";
replace = false;
}
if (line.indexOf("replaceNextLine") > -1) {
replace = true;
}
input2 = input2 += (line + "\n");
}
// line is not visible here.
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input2);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("data.txt");
fileOut.write(input2.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
e.printStackTrace();
}
}
public static void main(String[] args) {
replaceSelected("1 adam 20 M", "foobar");
}
}
If you run the code, it will replace next line after a line which is "replaceNextLine":
$ java FileLineReplace
asd
zxc
xcv
replaceNextLine
wer
qwe
----------------------------------
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe
My test file is (was)
asd
zxc
xcv
replaceNextLine
wer
qwe
After I run the program, the file looks like this and the line after the specified line is replaced.
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe

How can I print the average of the lines in this file?

I'm writing a program in Java which iterates over each line of a text file, this text file contains numbers which are on a separate line, I have successfully made the program read each line and print them to a new file.
However I'm trying to print the average of these numbers to the new file as well, I understand that I would have to treat each line as a float or double (as I'm using decimal numbers) but I'm unsure of how to do this, this is what I've got so far.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Run {
public static void main(String[] args) throws Exception {
Write(); //call Write method
}
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
//int mynewLine = Integer.parseInt(lineCut);
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}
Basically this is what you are doing
reading lines from a file
replacing ';' with a ','
writing this modified line to a new file
So in each of above operation, you have never treated the line to be a Number. To find average, you need to parse each line of number into real Number, Double.parseDouble("21.2") etc, and in each iteration, you know what to do :-)
For example:
double sum= 0;
int count = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ","); // replace ; with ,
//lineCut = line.substring(1, line.length());
int num = Double.parseDouble(lineCut);
sum = sum + num; count++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
br.write(String.valueOf(sum/count));
Not tested. I am considering each line has a number and nothing else. Remember your should check the valou on linecount to avoid an Exception during the conversion from String to float.
public static void Write() throws Exception {
String line, lineCut;
BufferedReader br = null; //initialise BR- reads text from file
BufferedWriter bw = null; //initialise BR- writes text to file
try
{
br = new BufferedReader(new FileReader("/Users/jbloggs/Documents/input.txt")); //input file
bw = new BufferedWriter(new FileWriter("/Users/jbloggs/Desktop/output.txt")); //output file
line = br.readLine(); // declare string equal to each line
float sum = 0;
int counter = 0;
while(line != null) { // iterate over each line
lineCut = line.replaceAll(";" , ",");
sum += Float.parseFloat(lineCut);
counter++;
bw.write(lineCut); // write each line to output file
bw.write("\n"); // print each line on a new line
line = br.readLine();
}
bw.write("Average = ");
bw.write(sum / counter);
bw.write("\n");
System.out.println("success"); //print if program works
br.close();
bw.close();
}
catch(Exception e){
throw(e); // throw exception
}
}
}

Read from source file and split the contents into two other separate files

My goal is that I wish to read from a file with the name "input.txt", which has 10 lines of text, and then write 5 lines from the original into two other files with the names "test1.txt" and "test2.txt". I'm using the following code, but it is not working - please help me.
import java.util.Scanner;
import java.io.*;
public class main {
public static void main (String args[]) throws FileNotFoundException, IOException{
BufferedReader br = new BufferedReader (new FileReader("bin/input.txt"));
File file = new File("bin/test2.txt");
BufferedWriter writer = new BufferedWriter(new FileWriter("bin/test.txt"));
Scanner sc = new Scanner (br);
int i = 0;
while (sc.hasNextLine()){
sc.nextLine();
i++;
System.out.print(i);
int n = (i+1)/2;
System.out.print("\n"+n);
writer.write(sc.nextLine().toString());
writer.newLine();
if (n==5){
writer.close();
}
}
if (sc != null){
sc.close();
}
}
}
this will read from single file and splitting content into two file.
int count = 0;
BufferedReader br = null;
FileWriter fileWriter1 = new FileWriter("G:\\test1.txt");
FileWriter fileWriter2 = new FileWriter("G:\\test2.txt");
try {
String currentLine;
br = new BufferedReader(new FileReader("G:\\input.txt"));
while ((currentLine = br.readLine()) != null) {
count++;
if (count <= 5) {
fileWriter1.write(currentLine + "\n");
} else {
fileWriter2.write(currentLine + "\n");
}
}
} finally {
if (br != null) {
br.close();
}
fileWriter1.close();
fileWriter2.close();
}
Create two BufferedWriter instead of one with two files and then follow the below procedure:
count <- 0
while scanner hasNextLine
do
string line <- scanner's next Line
if (count > 4) {
writer2.write line
} else {
writer1.write line
}
count <- count + 1
done
finally close all three resources.

Java readLine() is returning null

The "Number of Lines = 4" shows it's reading all 4 lines of the text file.
But then "Line read = null". I don't know why the readLine() method is not reading the first line.
import java.io.*;
public class TestLineRead {
public static void main (String[] args)
{
try
{
File tmpFileIn = new File("C:/Java/Employees.txt");
BufferedReader br = new BufferedReader (new InputStreamReader(
new FileInputStream(tmpFileIn)));
LineNumberReader lnr = new LineNumberReader(br);
int numOfLines = 0;
while (lnr.readLine() != null) {
numOfLines++;
}
String str = null;
System.out.println("Number of lines = " + numOfLines);
str = br.readLine();
System.out.println("Line read = " + str);
br.close();
}
catch (IOException e) { System.out.println("error: " + e.getMessage()); }
} // close main
} // close Class
I don't know why the readLine() method is not reading the first line.
It did, when you were counting lines.
This
while (lnr.readLine() != null) {
numOfLines++;
}
consumes lines. It returns null when there are no more lines left.

Categories