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();
}
}
Related
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
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();
}
}
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.
For some reason when I am trying to write an int called duration to a file called newSession and the program is done compiling and I open the file located on my desktop, every other file is fine (meaning the content I wanted to be written to that file was successfully) but newSession has random letters written in it. Why is this and can anybody explain why the int duration is not being written to the file newSession and instead random letters.
package kappa;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class Reader
{
public static void main(String[] args) throws FileNotFoundException, UnsupportedEncodingException, IOException
{
File dateFile = null;
Scanner reader = null;
try
{
String filePath = "/Users/john/Desktop/firstTime.txt";
Scanner reader2 = null;
while(true)
{
FileWriter fw = new FileWriter(filePath);
BufferedWriter bw = new BufferedWriter(fw);
File firstTime = new File(filePath);
firstTime.createNewFile();
bw.write("1");
bw.close();
reader2 = new Scanner(new File(filePath));
break;
}
if(reader2.nextInt() == 1)
{
dateFile = new File("/Users/john/Desktop/Kunja.txt");
dateFile.createNewFile();
reader = new Scanner(dateFile);
}
// if file doesnt exists, then create it
if (dateFile.exists())
{
FileWriter fw2 = new FileWriter(dateFile.getAbsoluteFile());
BufferedWriter bw2 = new BufferedWriter(fw2);
dateFile.createNewFile();
bw2.write("0");
bw2.close();
System.out.println("Done");
int duration;
String ans = JOptionPane.showInputDialog ("Enter the amount of problems per training session (with number in minutes):");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter the amount of problems per training session (with number in minutes):" );
}
duration = Integer.parseInt(ans);
System.out.println("Duration is " + duration);
int numSessions = (reader.nextInt() + 1);
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File("/Users/john/Desktop/"+fileName);
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
}
FileWriter fw3 = new FileWriter(newSession.getAbsoluteFile());
System.out.println("THE FILE PATH IS " + newSession.getAbsoluteFile());
BufferedWriter bw3 = new BufferedWriter(fw3);
bw3.write(duration);
bw3.close();
}else
{
int duration;
String ans = JOptionPane.showInputDialog ("Enter a number (only numbers please)");
while(!ans.matches("[0-9]+"))
{
ans = JOptionPane.showInputDialog ("Please re-enter a number (NOTHING ELSE!)" );
}
duration = Integer.parseInt(ans);
System.out.println(duration);
int numSessions = reader.nextInt();
System.out.println("Number of sessions is: " + numSessions);
String fileName = ("sessionNumber"+numSessions);
File newSession = new File("/Users/john/Desktop/"+fileName);
System.out.println(fileName);
if (!newSession.exists())
{
newSession.createNewFile();
System.out.println("IT DOES NOT EXIST!");
}
FileWriter fw = new FileWriter(newSession.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write(duration);
bw.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
}
BufferedWriter#write(int) takes a single character (represented by an int). If you want to write the textual representation of an integer, you'd have to convert it to a String yourself.
In short, replace:
bw3.write(duration);
With:
String durationString = String.valueOf(duration);
bw3.write(durationString, 0, durationString.length());
I am trying to read data from a text file (line by line) and I want to write into output file the lines I read from the flies.
Here is how I programmed my code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class read {
public static void main(String args[])
{
String input = null;
input = readFile();
writeFile(input);
}
public static void writeFile(String in)
{
String fileName = "output.txt";
//String payload = null;
try {
FileWriter fw = new FileWriter(fileName);
BufferedWriter bw =new BufferedWriter(fw);
bw.write(in);
System.out.println("Received "+in.length()+" bytes: ");
bw.close();
}
catch(IOException ex) {
System.out.println("Error writing to file '"+ fileName + "'");
}
}
public static String readFile()
{
String fileName = "temp.txt";
String line = null;
String Sentence = null;
try {
FileReader fr = new FileReader(fileName);
BufferedReader br = new BufferedReader(fr);
while((line = br.readLine()) != null) {
//Sentence += line+'\n';
Sentence = line +'\n';
}
br.close();
System.out.println("Sending file "+fileName);
return Sentence;
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
return null;
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
return null;
// Or we could just do this:
// ex.printStackTrace();
}
}
}
text file:
I returned##% from the City about three o'clock on that
May afternoon pretty well disgusted with life.
I had been three months in the Old Country, and was
fed up with it.
Output:
The read method reads first line from the text file and writes that line into output file...
I am new in programming and would really appreciate help!
For creating the output file, try this:
PrintWriter writer = new PrintWriter(filename, "UTF-8");
writer.println(in);
writer.close();
When you read from the file you should append the lines to your original variables by doing
Sentence += line+'\n';