Appending text to existing file without overwriting it - java

I'm adding some content into an existing file NameList.txt, which already contains some text there.
But when I run the program, it removes all the existing content before starting to write new ones.
Note: I also try to find where is the file ending line. E.g. by using while ((lines = reader.readLine()) == null), where the lines variable is of the type String.
public class AddBooks {
public static void main(String[] args) {
Path Source = Paths.get("NameList.txt");
Charset charset = Charset.forName("Us-ASCII");
try (
BufferedWriter write = Files.newBufferedWriter(Source, charset);
BufferedReader reader = Files.newBufferedReader(Source, charset);
) {
Scanner input = new Scanner(System.in);
String s;
String line;
int i = 0, isEndOfLine;
do {
System.out.println("Book Code");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Title");
s = input.nextLine();
write.append(s, 0, s.length());
write.append("\t \t");
System.out.println("Book Publisher");
s = input.nextLine();
write.append(s, 0, s.length());
write.newLine();
System.out.println("Enter more Books? y/n");
s = input.nextLine();
} while(s.equalsIgnoreCase("y"));
} catch (Exception e) {
// TODO: handle exception
}
}
}
My only requirement is to add new content to existing file.

Change your code like this!
BufferedWriter write = Files.newBufferedWriter(Source, charset, StandardOpenOption.APPEND);
And see this!
StandardOpenOption
2nd..
while ((str = in.readLine()) != null)
Appendix.. insert
writer.close();
before
} while(s.equalsIgnoreCase("y"));

Related

How can I delete lines of data in textfile using java? eg. my textfile is data.txt

From read the line needed to be deleted by the user to delete it
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Delete {
public static void main(String[] args) throws IOException {
File input = new File("data.txt");
FileReader fr = null;
Scanner ob = new Scanner(System.in);
// declare variable
String DeleteWord, str, newDeleteWord;
System.out.print("Enter word you want to delete: ");
DeleteWord = ob.nextLine();
newDeleteWord = (capitalize(DeleteWord));
try {
fr = new FileReader(input);
BufferedReader br = new BufferedReader(fr);
while ((str = br.readLine()) != null) {
if (str.contains(newDeleteWord)) {
System.out.println(str);
}
Scanner read = new Scanner(System.in);
int selection;
System.out.println("Confirm to delete his/her data?\n 1 for yes\n 2 for no");
selection = read.nextInt();
if (selection == 1)
if (str.contains(newDeleteWord)) {
str = "";
}
}
} finally {
fr.close();
}
}
public static String capitalize(String str1) {
if (str1 == null || str1.isEmpty()) {
return str1;
}
return str1.substring(0, 1).toUpperCase() + str1.substring(1);
}
}
How can I delete lines of data in textfile using java? eg. my textfile is data.txt
This is a possible solution:
File inputFile = new File("myFile.txt"); // File which we will read
File tempFile = new File("myTempFile.txt"); // The temporary file where we will write
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = yourString; // here is your line to remove
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim(); // we trim it and remove unecessary spaces
if(trimmedLine.equals(lineToRemove)) continue; // If it is equal to our line to remove then do not write it to our file!
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
inputFile.delete(); // we delete the file that we have so that we have no conflicts
boolean successful = tempFile.renameTo(inputFile);
OR
Reading all the lines in a list and filtering this list.
The quickest way is through Apache Commons-IO ( or you can implement it yourself)
Apache Commons:
List<String> lines = FileUtils.readLines(file);
List<String> updatedLines = lines.stream().filter(s -> !s.contains(searchString)).collect(Collectors.toList());
FileUtils.writeLines(file, updatedLines, false);

When importing a txt file, is there a way to specify how you want it formatted? [duplicate]

How can I open a .txt file and read numbers separated by enters or spaces into an array list?
Read file, parse each line into an integer and store into a list:
List<Integer> list = new ArrayList<Integer>();
File file = new File("file.txt");
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(file));
String text = null;
while ((text = reader.readLine()) != null) {
list.add(Integer.parseInt(text));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
}
}
//print out the list
System.out.println(list);
A much shorter alternative is below:
Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
} else {
scanner.next();
}
}
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.
Good news in Java 8 we can do it in one line:
List<Integer> ints = Files.lines(Paths.get(fileName))
.map(Integer::parseInt)
.collect(Collectors.toList());
try{
BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}finally{
in.close();
}
This will read line by line,
If your no. are saperated by newline char. then in place of
System.out.println (strLine);
You can have
try{
int i = Integer.parseInt(strLine);
}catch(NumberFormatException npe){
//do something
}
If it is separated by spaces then
try{
String noInStringArr[] = strLine.split(" ");
//then you can parse it to Int as above
}catch(NumberFormatException npe){
//do something
}
File file = new File("file.txt");
Scanner scanner = new Scanner(file);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
if (scanner.hasNextInt()) {
integers.add(scanner.nextInt());
}
else {
scanner.next();
}
}
System.out.println(integers);
import java.io.*;
public class DataStreamExample {
public static void main(String args[]){
try{
FileWriter fin=new FileWriter("testout.txt");
BufferedWriter d = new BufferedWriter(fin);
int a[] = new int[3];
a[0]=1;
a[1]=22;
a[2]=3;
String s="";
for(int i=0;i<3;i++)
{
s=Integer.toString(a[i]);
d.write(s);
d.newLine();
}
System.out.println("Success");
d.close();
fin.close();
FileReader in=new FileReader("testout.txt");
BufferedReader br=new BufferedReader(in);
String i="";
int sum=0;
while ((i=br.readLine())!= null)
{
sum += Integer.parseInt(i);
}
System.out.println(sum);
}catch(Exception e){System.out.println(e);}
}
}
OUTPUT::
Success
26
Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file.
input-convert-Write-Process... its that simple.

Java - Reading a line from a file containing text and number

I'm just trying to do an exercise where I have to read a particular file called test.txt in the following format:
Sampletest 4
What I want to do is that I want to store the text part in one variable and the number in another. I am still a beginner so I had to google quite a bit to find something that would at-least work, here what I got so far.
public static void main(String[] args) throws Exception{
try {
FileReader fr = new FileReader("test.txt");
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
System.out.println(str);
}
br.close();
} catch(IOException e) {
System.out.println("File not found");
}
Use a Scanner, which makes reading your file way easier than DIY code:
try (Scanner scanner = new Scanner(new FileInputStream("test.txt"));) {
while(scanner.hasNextLine()) {
String name = scanner.next();
int number = scanner.nextInt();
scanner.nextLine(); // clears newlines from the buffer
System.out.println(str + " and " + number);
}
} catch(IOException e) {
System.out.println("File not found");
}
Note the use of the try-with-resources syntax, which closes the scanner automatically when the try is exited, usable because Scanner implements Closeable.
You just need:
String[] parts = str.split(" ");
And parts[0] is the text (sampletest)
And parts[1] is the number 4
It seems like you are reading the whole file content (from test.txt file) line by line, so you need two separate List objects to store the numeric and non-numeric lines as shown below:
String str;
List<Integer> numericValues = new ArrayList<>();//stores numeric lines
List<String> nonNumericValues = new ArrayList<>();//stores non-numeric lines
while((str = br.readLine()) != null) {
if(str.matches("\\d+")) {//check line is numeric
numericValues.add(str);//store to numericList
} else {
nonNumericValues.add(str);//store to nonNumericValues List
}
}
If you are sure the format is always for each line in the file.
String str;
List<Integer> intvalues = new ArrayList<Integer>();
List<String> charvalues = new ArrayList<String>();
try{
BufferedReader br = new BufferedReader(new FileReader("test.txt"));
while((str = br.readLine()) != null) {
String[] parts = str.split(" ");
charvalues.add(parts[0]);
intvalues.add(new Integer(parts[0]));
}
}catch(IOException ioer) {
ioer.printStackTrace();
}
You can use java utilities Files#lines()
Then you can do something like this. Use String#split() to parse each line with a regular expression, in this example i use a comma.
public static void main(String[] args) throws IOException {
try (Stream<String> lines = Files.lines(Paths.get("yourPath"))) {
lines.map(Representation::new).forEach(System.out::println);
}
}
static class Representation{
final String stringPart;
final Integer intPart;
Representation(String line){
String[] splitted = line.split(",");
this.stringPart = splitted[0];
this.intPart = Integer.parseInt(splitted[1]);
}
}

Take Strings from Text file and assign each line to value (2 at a time and insert into LinkedHashMap)

What I'm trying to do is, load a Text file, then take the values from each line and assign them to a variable in my program. Every two lines, I will insert them into a LinkedHashMap (As a pair)
The problem with a buffered reader is, all I can seem to do is, read one line at a time.
Here is my current code:
public static void receiver(String firstArg) {// Receives
// Input
// File
String cipherText;
String key;
String inFile = new File(firstArg).getAbsolutePath();
Path file = new File(inFile).toPath();
// File in = new File(inFile);
try (InputStream in = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(
new InputStreamReader(in))) {
String line = null;
while ((line = reader.readLine()) != null) {
// System.out.println(line);
String[] arrayLine = line.split("\n"); // here you are
// splitting
// with whitespace
cipherText = arrayLine[0];
// key = arrayLine[1];
System.out.println(arrayLine[0] + " " + arrayLine[1]);
cipherKeyPairs.put(arrayLine[0], arrayLine[1]);
}
} catch (IOException x) {
System.err.println(x);
}
The problem is, it can't find the arrayLine[1] (for obvious reasons). I need it to read two lines at a time without the array going out of bounds.
Any idea how to do this, so that I can store them into my LinkedHashMap, two lines at a time as separate values.
You can overcome this issue by inserting in the List every 2 lines reading.
A description for this code is that: "Bold is the true case"
Read the first line (count is 0)
If (secondLine is false) ==> Save the line to CipherText variable, make secondLine = true
Else If (secondLine is true) ==> Add to list (CipherText, line), make secondLine = false
Read the second line (count is 1)
If (secondLine is false) ==> Save the line to CipherText variable, make secondLine = true
Else If (secondLine is true) ==> Add to list (CipherText, line), make secondLine = false
String cipherText;
boolean secondLine = false;
String inFile = new File(firstArg).getAbsolutePath();
Path file = new File(inFile).toPath();
try {
InputStream in = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(new InputStreamReader(in))) {
String line = null;
while ((line = reader.readLine()) != null) {
if (!secondLine) //first line reading
{
cipherText = line;
secondLine = true;
}
else if (secondLine) //second line reading
{
cipherKeyPairs.put(cipherText, line);
secondLine = false;
}
}
} catch (IOException x) {
System.err.println(x);
}
See if this works for you. I just edited your code. it might not be the best answer.
public static void receiver(String firstArg) {// Receives
// Input
// File
String cipherText;
String key;
String inFile = new File(firstArg).getAbsolutePath();
Path file = new File(inFile).toPath();
// File in = new File(inFile);
try (InputStream in = Files.newInputStream(file);
BufferedReader reader = new BufferedReader(
new InputStreamReader(in))) {
String line = null;
List<String> lines = new ArrayList();
while ((line = reader.readLine()) != null) {
lines.add(line);//trim line first though and check for empty string
}
for(int i=1;i<lines.size();i++){
cipherText = arrayLine[i];
// key = arrayLine[1];
System.out.println(arrayLine[i] + " " + arrayLine[i-1]);
cipherKeyPairs.put(arrayLine[i-1], arrayLine[i]);
}
} catch (IOException x) {
System.err.println(x);
}
}

Java file read problem

I have a java problem. I am trying to read a txt file which has a variable number of integers per line, and for each line I need to sum every second integer! I am using scanner to read integers, but can't work out when a line is done. Can anyone help pls?
have a look at the BufferedReader class for reading a textfile and at the StringTokenizer class for splitting each line into strings.
String input;
BufferedReader br = new BufferedReader(new FileReader("foo.txt"));
while ((input = br.readLine()) != null) {
input = input.trim();
StringTokenizer str = new StringTokenizer(input);
String text = str.nextToken(); //get your integers from this string
}
If I were you, I'd probably use FileUtils class from Apache Commons IO. The method readLines(File file) returns a List of Strings, one for each line. Then you can simply handle one line at a time.
Something like this:
File file = new File("test.txt");
List<String> lines = FileUtils.readLines(file);
for (String line : lines) {
// handle one line
}
(Unfortunately Commons IO doesn't support generics, so the there would be an unchecked assignment warning when assigning to List<String>. To remedy that use either #SuppressWarnings, or just an untyped List and casting to Strings.)
This is, perhaps, an example of a situation where one can apply "know and use the libraries" and skip writing some lower-level boilerplate code altogether.
or scrape from commons the essentials to both learn good technique and skip the jar:
import java.io.*;
import java.util.*;
class Test
{
public static void main(final String[] args)
{
File file = new File("Test.java");
BufferedReader buffreader = null;
String line = "";
ArrayList<String> list = new ArrayList<String>();
try
{
buffreader = new BufferedReader( new FileReader(file) );
line = buffreader.readLine();
while (line != null)
{
line = buffreader.readLine();
//do something with line or:
list.add(line);
}
} catch (IOException ioe)
{
// ignore
} finally
{
try
{
if (buffreader != null)
{
buffreader.close();
}
} catch (IOException ioe)
{
// ignore
}
}
//do something with list
for (String text : list)
{
// handle one line
System.out.println(text);
}
}
}
This is the solution that I would use.
import java.util.ArrayList;
import java.util.Scanner;
public class Solution1 {
public static void main(String[] args) throws IOException{
String nameFile;
File file;
Scanner keyboard = new Scanner(System.in);
int total = 0;
System.out.println("What is the name of the file");
nameFile = keyboard.nextLine();
file = new File(nameFile);
if(!file.exists()){
System.out.println("File does not exit");
System.exit(0);
}
Scanner reader = new Scanner(file);
while(reader.hasNext()){
String fileData = reader.nextLine();
for(int i = 0; i < fileData.length(); i++){
if(Character.isDigit(fileData.charAt(i))){
total = total + Integer.parseInt(fileData.charAt(i)+"");
}
}
System.out.println(total + " \n");
}
}
}

Categories

Resources