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
Related
So I have created this method which at the end displays the whole line because i am displaying the array after converting and editing it. So my Question is how can i know overwrite the array to the same line i grabbed it from. thanks in advance and here is my code.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String str;
while ((str = br.readLine()) != null) {
if (str.contains(accountNumber)) {
String[] array = str.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);}
break;
}
}
} catch (Exception ex) {
System.out.println(ex);
}
}
i am using string accountNumber to grab the specific line that i need. after getting the line i am changing it to an array while splitting the index with str.split(" "); . After that i know that i need to edit index number [3]. so i do so and then i put it back into the array. the final thing i need to do is to right the array back now.
You can keep track of the input from the file you are reading and write it back with the modified version.
public void getData(String path, String accountNumber) {
try {
FileInputStream fis = new FileInputStream(path);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
System.out.println("Please Enter the Deposit amount That you would like to add.");
Scanner sn = new Scanner (System.in);
int add = sn.nextInt();
String line; // current line
String input = ""; // overall input
while ((line = br.readLine()) != null) {
if (line.contains(accountNumber)) {
String[] array = line.split(" ");
int old = Integer.parseInt(array[3]);
int Sum= old + add;
String Sumf = Integer.toString(Sum);
array[3] = Sumf;
// rebuild the 'line' string with the modified value
line = "";
for (int i = 0; i < array.length; i++)
line+=array[i]+" ";
line = line.substring(0,line.length()-1); // remove the final space
}
// add the 'line' string to the overall input
input+=line+"\n";
}
// write the 'input' String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream(path);
fileOut.write(input.getBytes());
fileOut.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
This is how i understand the question that you have a file you will read it line by line and will make some changes and want to write it again at the same position. Create a new temp file and write the contents to the temp file, if changed write the changed result if not write it as it is.
And at last rename the temp to your original file name
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.
I have to write a program that supports extensions. I have a problem with FileNotFound Exception. Program asks about the name of the file. My task is to write an special information when there is no file like given, and ask again until user will write an existing file name. I know how to write an special information that there is no file, but I don't know how to ask again about the name of the file (I only know that it must be done using readNP method).
Here is the code:
import.java.io.*;
import java.util.* ;
class Reading{
static BufferedReader sysin =
new BufferedReader(new InputStreamReader(System.in));
String readNP() throws IOException{
// ask about file name
System.out.print("file name ");
String filename;
filename = sysin.readLine() ;
return filename.trim();
}
void read(ArrayList<Double> a) throws IOException{
// reading from file
int nr=1 ;
String name = readNP();
BufferedReader br = new BufferedReader(new FileReader(name));
String line;
while ((line = br.readLine()) != null){
a.add(new Double(line));
nr++;
}
br.close() ;
}
}
class Exceptions{
static void average(ArrayList<Double> a){
double s=0.0d;
for (int i=0; i<a.size(); i++)
s+=a.get(i).doubleValue();
System.out.println("average from numbers in table: "+s/a.size());
}
public static void main(String[] args)throws IOException{
ArrayList<Double> a = new ArrayList<Double>();
Reading r = new Reading();
try{
r.read(a);
average(a);
} catch(FileNotFoundException e){
System.out.println("File not found");
}
}
}
I would add test for existence of file name (and for that it's not the name of the directory) into your readNP() function:
String readNP() throws IOException{
// ask about file name
for (;;) {
System.out.print("file name ");
String filename;
filename = sysin.readLine();
File f = new File(filename);
if (f.exists() && !f.isDirectory()) return filename.trim();
System.out.println("file absent"); //message if the there is no file with this name
}
}
This is my question :
a method readLine that reads a line from the file specified in fileName and returns the line a String.
What I am trying to do is I read and write some info into text file using eclipse. And here are my codes :
public class FileController {
private String fileName;
public FileController(){
String fileName = "student.txt";
}
public FileController(String fileName){
this.fileName = fileName;
}
public String readLine(){
String line ="";
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line;
}
public void writeLine(String input){
try{
FileWriter fw = new FileWriter(fileName,true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter outFile = new PrintWriter(bw);
outFile.println(input);
outFile.close();
}catch(IOException exception){
System.out.println(exception);
}
}
public static void main (String [] args){
FileController fc = new FileController("student.txt");
String input = "1234567H;Gabriel;23/12/1994;56;67;87";
fc.readLine();
fc.writeLine(input);
}
This works perfectly by adding the record into the text file. However, the console there doesn't shows the result. So from what I know it's the mistake was at readLine(). When I used void it works perfectly. But the question requests me to return a String. Anybody know how to solve this?
when I do println within the while loop there's record stored in there. I guess the programme took the String file= ""; this line and return the result. So how can I take the result of line in while loop and replace with the initialization?
You are overwriting the line in while loop:
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line = stud.toString();
}
So this means that only last line will get passed to student [most likely blank line] and it might not print anything or even an exception might come. Use StringBuffer and append the string and then return that.
EDIT:
Try this.
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}
EDIT:
If above code also returns blank then most likely issue is Strudent "toString()" method. It might be returning blank.
EDIT:
public String readLine(){
StringBuffer line =new StringBuffer();
try{
FileReader fr = new FileReader(fileName);
Scanner sc = new Scanner(fr);
while(sc.hasNextLine()){
Student stud = new Student(sc.nextLine());
line.append(stud.toString());
line.append("\n");
}
fr.close();
}catch(FileNotFoundException exception){
System.out.println("File " + fileName + " was not found");
}catch(IOException exception){
System.out.println(exception);
}
return line.toString();
}
I'm writing code which deletes a word out of a text file when the user inputs it but I cant seem to get the scanner part to work
public static void Option2Method() throws IOException
{
File inputFile = new File("wordlist.txt");
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
Scanner writer =new Scanner(tempFile);
String currentLine;
while((currentLine = reader.nextLine()) != null)
{
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.print(currentLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Scanner is not meant to write files, hence does not have a write() method. You can use BufferedWriterinstead.
Example:
public static void Option2Method() throws IOException {
File inputFile = new File("wordlist.txt");
FileWriter fstream = new FileWriter("TempWordlist.txt", true);
BufferedWriter writer = new BufferedWriter(fstream);
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.write(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
}
Using PrintWriter:
File inputFile = new File("wordlist.txt");
PrintWriter writer = new PrintWriter(new BufferedWriter(new FileWriter("TempWordlist.txt", true)));
File tempFile = new File("TempWordlist.txt");
String lineToRemove = JOptionPane.showInputDialog(null, "Enter a word to remove");
Scanner reader = new Scanner(inputFile);
while (reader.hasNextLine()) {
String trimmedLine = reader.nextLine().trim();
if (trimmedLine.equals(lineToRemove))
continue;
writer.print(trimmedLine + "\n");
}
reader.close();
writer.close();
inputFile.delete();
tempFile.renameTo(inputFile);
Scanner doesn't have a print method. It is used to scan a file and read data from it.
If you want to write to a file, use this or that or just google "java write to file"