Write to file line by line - java

So my input file has some sentences, and i want to reverse the words in each sentence and keep the same order of sentences. I then need to print to a file. my problem is that my output file is only printing my last sentence, reversed.
import java.util.*;
import java.io.*;
public class Reverser { //constructor Scanner sc = null ; public
Reverser(File file)throws FileNotFoundException, IOException {
sc = new Scanner (file); }
public void reverseLines(File outpr)throws FileNotFoundException, IOExeption{
//PrintWriter pw = new PrintWriter(outpr);
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter fw = new FileWriter(outpr);
BufferedWriter bw = new BufferedWriter(fw);
for(String str: wordsarraylist) {
bw.write(str + " ");
bw.newLine();
bw.close();
}
} }
}

That's because each time you loop, you reopen the file in overwrite mode.
Open the file before you start looping instead.
Don't use the append option here, it'll just make you open/close the file needlessly.

Related

How to write data from an array into a text file?

I am writing a simple program which asks the user for his name, surname and age and then saves it to a text file, however the previous data gets deleted.
I am already reading the text file and can display it but I cant write it to the text file.
This is the code I am using:
import java.util.Scanner;
import java.io.*;
public class UserData{
public static void main (String args[]) throws IOException{
//Initialisations
Scanner scan = new
Scanner(System.in);
File UserData = new File(PATH OF FILE);
BufferedWriter b = new BufferedWriter(new FileWriter(UserData));
//Reader for Writer Old Data
String text[] = new String[10];
int count = 0;
String path = PATH OF FILE;
BufferedReader reader = new BufferedReader(new FileReader(path));
String line = null;
while ((line = reader.readLine()) != null){
text[count] = line;
count++;
}
PrintWriter pr = new PrintWriter(PATH OF FILE);
for (int I=0; I<text.length ; I++)
{
pr.println(text);
}
//Writer
System.out.println("Enter your name");
String name = scan.nextLine();
pr.println(name);
b.newLine();
System.out.println("Enter your surname");
String surname = scan.nextLine();
pr.println(surname);
b.newLine();
System.out.println("Enter your age");
int age = scan.nextInt();
pr.println(String.valueOf(age));
pr.close();
}
}
FileWriter class has a constructor
public FileWriter(File file,
boolean append)
throws IOException
Constructs a FileWriter object given a File object.
In Your code - Change line no 9 to
BufferedWriter b = new BufferedWriter(new FileWriter(UserData),true);
If the second argument is true, then bytes will be written to the end of the file rather than the beginning.
Here is the specification:
Class FileWriter Constructors

Java how to update String of Text file

I want to update content of my Text file that is created using Scanner class of Java. Each line of text file consists of 4 strings. I want to update 2 strings of every line whenever user updates values. I've tried different codes but nothing is working. Kindly help me to update my values. what should be solution?
import java.util.*;
import java.io.*;
import javax.swing.*;
public class File2
{
public static void main(String args[])
{
Scanner obj=new Scanner(System.in);
System.out.println("\f");
System.out.println("Enter Material");
String material=obj.next();
String color="Tendra Black";
System.out.println("Enter quantity");
String quantity=obj.next();
System.out.println("Enter roll");
String roll=obj.next();
Scanner fileIn = null;
try
{
fileIn = new Scanner (new FileInputStream("Stock.txt"));
}
catch(FileNotFoundException f)
{
JOptionPane.showMessageDialog(null,"File not found. Please specify coreect location.");
}
if(fileIn.hasNext())
{
while(fileIn.hasNext())
{
File log= new File("Stock.txt");
String details = fileIn.nextLine();
StringTokenizer tokenizer = new StringTokenizer(details,"-");
String materialAvailable=null;
String colorAvailable=null;
String quantityAvailable=null;
String rollAvailable=null;
while(tokenizer.hasMoreTokens())
{
materialAvailable=tokenizer.nextToken();
colorAvailable=tokenizer.nextToken();
quantityAvailable=tokenizer.nextToken();
rollAvailable=tokenizer.nextToken();
if((colorAvailable.equalsIgnoreCase(color)))
{
int val1Q=Integer.parseInt(quantityAvailable);
int val2Q=Integer.parseInt(quantity);
int val1R=Integer.parseInt(rollAvailable);
int val2R=Integer.parseInt(roll);
int quanF=val1Q+val2Q;
int rollF=val1R+val2R;
//quantityAvailable=Integer.toString(quanF);
//rollAvailable=Integer.toString(rollF);//file readTill
details=details.replaceAll(quantityAvailable,Integer.toString(quanF));
details=details.replaceAll(rollAvailable,Integer.toString(rollF));
}
try{
FileWriter fw = new FileWriter(log);
fw.write(details);
fw.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
}
}
You just need to open the file to overwrite instead of append, use a FileOutputStream and set the append value to false, like this
try{
FileOutputStream fw = new FileOutputStream(log, false);
fw.write(details);
fw.close();
}

File Comparer doesn't write result to file

Hiho guys,
I am writing an easy application, which should open two .txt files, take first line of the first file and then iterate through every line of second file. If it finds the same String in second file, then it should write this string to outputfile.txt with nextline. After the loop over the second file is done, it should take the second line from the first line and search for the same String and if finds then writes it with nextline.
I've tried it by myself but it does nothing, I mean it doesn't put any text into outputfile.txt, even if I am sure that there are same words.
package com.company;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
String sourceFileName = "C:\\Users\\Maciej\\IdeaProjects\\spring5webapp\\FileTextChecker\\src\\com\\company\\BootfileRO.txt";
String comparingFileName = "C:\\Users\\Maciej\\IdeaProjects\\spring5webapp\\FileTextChecker\\src\\com\\company\\BootfileSK.txt";
String outputFileName = "C:\\Users\\Maciej\\IdeaProjects\\spring5webapp\\FileTextChecker\\src\\com\\company\\output.txt";
System.out.println("Starting ... ");
File file1 = new File(sourceFileName);
File file2 = new File(comparingFileName);
PrintWriter file3 = new PrintWriter(outputFileName);
String line1 = "";
String line2 = "";
Scanner scan1 = new Scanner(file1);
Scanner scan2 = new Scanner(file2);
while(scan1.hasNextLine()){
line1 = scan1.nextLine();
while(scan2.hasNextLine()){
line2 = scan2.nextLine();
if(line1.equals(line2)){
file3.println(line1);
}
else{
continue;
}
}
}
file3.close();
// Comparer comparer = new Comparer(sourceFileName, comparingFileName, oFN);
// comparer.compare();
// CompareByScanner compareBYScanner = new CompareByScanner(sourceFileName, comparingFileName, outputFileName);
// compareBYScanner.compare();
}
}
To be honest, it looks like the "equals" function can't find the same strings, but I am sure they exists.
The problem here is that scan2 never resets, therefore after comparing the first line of file1, scan2.hasNextLine() will return false and therefore does not compare any further lines. Instead, set scan2 equal to a new Scanner at every iteration of the scan1 loop. This will set it to the start of the file. Then, after scanning the file, close the Scanner. New code:
package test;
import java.io.*;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Scanner;
public class TestMain {
public static void main(String[] args) throws IOException {
String sourceFileName = "src/output/compare1.txt";
String comparingFileName = "src/output/compare2.txt";
String outputFileName = "src/output/output.txt";
System.out.println("Starting ... ");
File file1 = new File(sourceFileName);
File file2 = new File(comparingFileName);
PrintWriter file3 = new PrintWriter(outputFileName);
String line1 = "";
String line2 = "";
Scanner scan1 = new Scanner(file1);
Scanner scan2;
while(scan1.hasNextLine()){
line1 = scan1.nextLine();
scan2 = new Scanner(file2);
while(scan2.hasNextLine()){
line2 = scan2.nextLine();
System.out.println("Line 1: " + line1 + "\n" + "Line 2: " + line2);
if(line1.equals(line2)){
file3.println(line1);
}
}
scan2.close();
}
file3.close();
// Comparer comparer = new Comparer(sourceFileName, comparingFileName, oFN);
// comparer.compare();
// CompareByScanner compareBYScanner = new CompareByScanner(sourceFileName,
comparingFileName, outputFileName);
// compareBYScanner.compare();
}
}

java cannot create file by 3 methods

I have a test.txt in my active directory.I need to create three methods:
First one has to create an output file and reverse the order of the lines.
Second the order of the words
The third the order of the lines and the words.
test.txt contains the input.
I developed every method to work on its own but somehow when I call all three at the same time it doesnt seem to work.
What am i doing wrong?
This is my main:
import java.io.*;
public class DemoReverser {
public static void main (String [] args)
throws IOException, FileNotFoundException {
Reverser r = new Reverser(new File("test.txt"));
r.completeReverse(new File("out3.txt"));
r.reverseEachLine(new File("out2.txt"));
r.reverseLines(new File("out1.txt"));
} }
and this is my class.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null ;
Scanner sc2 = null;
//constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file)throws FileNotFoundException, IOException{
sc = new Scanner (file);
}
//this method reverses the order of the lines in the output
//prints to output file specified in argument.
public void reverseLines(File outpr)throws FileNotFoundException, IOException{
List<String> wordsarraylist = new ArrayList<String>();
while(sc.hasNextLine()){
wordsarraylist.add(sc.nextLine());
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
//this method reverses the order of the words in each line of the input
//and prints it to output file specified in argument.
public void reverseEachLine(File outpr)throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
//this methhod reverses the order of the words in each sentence of the input
//then writes it to output file specified in argument
//then uses the output file as input and reverses the order of the sentences
//then overwrites the ouput file with the result
//the output file will contain the input sentences with their words reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException, IOException{
while(sc.hasNextLine()){
String sentence = sc.nextLine();
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner (outpr);
List<String> wordsarraylist = new ArrayList<String>();
while(sc2.hasNextLine()){
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr,true);
for(String str: wordsarraylist) {
writer.write(str+System.lineSeparator());
}
writer.flush();
writer.close();
}
}
When I run the program, out1 file gests created, which is the output file for my first method but it is empty. I don't get out2 file created by second method and out3 is fine.
What am I doing wrong? What is missed
Add writer.flush(); before writer.close(); in all three methods
And other thing - Scanner is initialized with File only once in constructor. It has to be re-initialized in other methods.
sc = new Scanner (file); // the scanner should be available in all three methods
For catching exceptions, use
try{
// your code
}catch(Exception err){
err.printStackTrace();
}
After running your code, output3.txt is generated (First method call). Later Scanner is not available since end of the file has been reached.
Fix : Scanner should be re-initialized for next two methods.
EDIT: ( Updating answer with your chat feedback)
1) Create three scanners sc1,sc2 and sc3 due to your limitations. I would suggest to re-initialize the scanner in every method with the file being worked upon.
2) String reversal in easier way without using StringBuffer reverse() API ( For learning purpose)
int length = str.length();
String reverse = "";
for ( int i = length - 1 ; i >= 0 ; i-- ){
reverse = reverse + str.charAt(i);
}
It's possible if you haven't write permission where you currently trying. So you get an error when testing.
However you have made some few mistakes in code. reverseEachLine method was not worked and you should not waste code to create completeReverse method. Please note following things.
Construct the Scanner when you need it
Remember to close the Scanner
Write processed file after closing the Scanner
Remove append if not necessary in Filewriter
Remember to flush FileWriter
Identify similarities and relationships between methods (complete reverse is a combination of line reverse and word reverse)
public class MyReverser {
private File inputFile;
public MyReverser(File file) {
this.inputFile = file;
}
public void reverseLines(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new java.util.Scanner(inputFile);
List<String> wordsarraylist = new ArrayList<String>();
while (sc.hasNextLine()) {
wordsarraylist.add(sc.nextLine());
}
sc.close();
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, false);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
public void reverseEachLine(File outpr) throws FileNotFoundException, IOException {
Scanner sc = new Scanner(inputFile);
ArrayList<List<String>> wordsarraylist = new ArrayList<List<String>>();
while (sc.hasNextLine()) {
String sentence = sc.nextLine();
List words = Arrays.asList(sentence.split(" "));
Collections.reverse(words);
wordsarraylist.add(words);
}
FileWriter writer = new FileWriter(outpr, false);
for (List<String> list : wordsarraylist) {
for (String string : list) {
writer.append(string + " ");
}
writer.append(System.lineSeparator());
}
writer.flush();
writer.close();
}
public void completeReverse(File outpr) throws FileNotFoundException, IOException {
//reverse lines first
reverseLines(outpr);
//then reverse words
reverseEachLine(outpr);
}
}
The scenario here was the scanners were instance variables and once read in one of your operations method, it won't have more to read when you call the next method from Demo class. Have made the changes to read the sentences and store it in the instance, so that it can be reused in each method.
import java.util.*;
import java.io.*;
public class Reverser {
Scanner sc = null;
Scanner sc2 = null;
boolean hasReadFile;
List<String> fileLinesList;
// constructor takes input file and initialize scanner sc pointing at input
public Reverser(File file) throws FileNotFoundException, IOException {
sc = new Scanner(file);
hasReadFile = false;
fileLinesList = new ArrayList<>();
}
// this method reverses the order of the lines in the output
// prints to output file specified in argument.
public void reverseLines(File outpr) throws FileNotFoundException,
IOException {
List<String> wordsarraylist = new ArrayList<String>();
readFile();
for (String sentence : fileLinesList) {
wordsarraylist.add(sentence);
}
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
// this method reverses the order of the words in each line of the input
// and prints it to output file specified in argument.
public void reverseEachLine(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
}
private void readFile() {
if (!hasReadFile) {
while (sc.hasNextLine()) {
fileLinesList.add(sc.nextLine());
}
fileLinesList = Collections.unmodifiableList(fileLinesList);
hasReadFile = true;
}
}
// this methhod reverses the order of the words in each sentence of the
// input
// then writes it to output file specified in argument
// then uses the output file as input and reverses the order of the
// sentences
// then overwrites the ouput file with the result
// the output file will contain the input sentences with their words
// reversed
// and the order of sentences reversed.
public void completeReverse(File outpr) throws FileNotFoundException,
IOException {
readFile();
for (String sentence : fileLinesList) {
String[] words = sentence.split(" ");
ArrayList<String> wordsarraylist2 = new ArrayList<String>(
Arrays.asList(words));
Collections.reverse(wordsarraylist2);
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist2) {
writer.write(str + " ");
}
writer.write(System.lineSeparator());
writer.flush();
writer.close();
}
sc2 = new Scanner(outpr);
List<String> wordsarraylist = new ArrayList<String>();
while (sc2.hasNextLine()) {
wordsarraylist.add(sc2.nextLine());
}
Collections.reverse(wordsarraylist);
PrintWriter erase = new PrintWriter(outpr);
erase.print("");
// erase.flush();
erase.close();
FileWriter writer = new FileWriter(outpr, true);
for (String str : wordsarraylist) {
writer.write(str + System.lineSeparator());
}
writer.flush();
writer.close();
}
}

how to read and write the answer in file i/o

i have this code i am working on i can read from file ,but i cant save the answer to my txt file .also how do i recall to do other operation on same number .i need a tips on how to do that.
package x;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class x {
public static void main(String args[]) throws FileNotFoundException {
//creating File instance to reference text file in Java
File text = new File("C:\\Users\\user\\Desktop\\testScanner.txt");
//Creating Scanner instnace to read File in Java
Scanner scnr = new Scanner(text);
//Reading each line of file using Scanner class
int lineNumber = 1;
while(scnr.hasNextLine()){
String line = scnr.nextLine();
int foo = Integer.parseInt(line);
System.out.println("===================================");
System.out.println("line " + lineNumber + " :" + line);
foo=100*foo;
lineNumber++;
System.out.println(" foo=100*foo " + lineNumber + " :" + foo);
}
}
}
you need to use a filewriter to write a file and filereader to write a file. you also need to import java.io. here is an example code:
import java.io.*;
public class FileRead{
public static void main(String args[])throws IOException{
File file = new File("Hello1.txt");
// creates the file
file.createNewFile();
// creates a FileWriter Object
FileWriter writer = new FileWriter(file);
// Writes the content to the file
writer.write("This\n is\n an\n example\n");
writer.flush();
writer.close();
//Creates a FileReader Object
FileReader fr = new FileReader(file);
char [] a = new char[50];
fr.read(a); // reads the content to the array
for(char c : a)
System.out.print(c); //prints the characters one by one
fr.close();
}
}

Categories