As in the tittle , i want to write my text from back and enter to the text file . In first , i read the text from the text file , next i want to save it in text file , but writing by the end of. I don't have any ideas how to fix my code . My code read the text file , and write the text file , but in the same order , from beginning to ending.
Example how it must work:
input text:
aaaaa
bbbb
ccc
dd
f
output text:
f
dd
ccc
bbbb
aaaaa
My code:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
public class Loading {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(
"file.txt.txt"));
String line, txt = "";
String[] splittedLine;
while ((line = br.readLine()) != null) {
txt += linia + "\n";
splittedLine = line.split(" ");
}
System.out.println(txt);
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("file2"));
bw.write(txt);
bw.newLine();
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Read File to String
Write String data to File starting from end.
For lines, use String array to store data from file and then traverse from end to start of array.
Here is complete program.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
import java.util.List;
public class Loading {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(
"DB.xml"));
String line, txt = "";
List<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
System.out.println(txt);
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("file2"));
for(int i=lines.size()-1; i>=0; i--){
bw.write(lines.get(i));
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You're going to want a list of lines, since you don't know the number of entries beforehand, so you want something that can grow with your code.
List<String> lines = new ArrayList<String>();
And add all your lines to it
while ((line = br.readLine()) != null) {
lines.add(line);
}
Then write them to your file in reverse order:
for(int i = lines.size() - 1; i >= 0; i--) {
bw.write(lines.get(i));
bw.newLine();
}
Your code is concatenating the string incorrectly. It needs to add the line text to the beginning of the string rather than at the end if you are trying to reverse the order.
txt = line + txt + "\n"; //original: txt += linia + "\n"
But it would be better to use a StringBuilder object to handle the concatenation for you. Something like...
StringBuilder txt = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
txt.insert(0, line + "\n");
}
System.out.println(txt.toString());
I do agree that the array approach in the other answers would also work and is probably a little easier to read and maintain. But the StringBuilder approach is closer to what you already have.
It should work:
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.util.ArrayList;
/**
*
* #author
*/
public class Read {
public static void main(String[] args) {
try {
BufferedReader br = new BufferedReader(new FileReader(
"D:/file.txt"));
String line, txt = "";
ArrayList<String> lines = new ArrayList<String>();
while ((line = br.readLine()) != null) {
lines.add(line);
}
System.out.println(txt);
br.close();
BufferedWriter bw = new BufferedWriter(new FileWriter("D:/file2.txt"));
for(int i = lines.size()-1; i>=0; i--){
bw.write(lines.get(i));
bw.newLine();
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Related
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);
I have a CSV file with some data and it also has a lot of invalid data in it. How can I print only the valid data and leave rest of it?
My data is like this:-
1,Ron,1234,XYZ
2,Harry,214,SDA
3,Kent,1786,GHI
SAMNE:MANNS;ndndo
kdbg;obmgdf;brhj
I want to print only the first 3 lines and remove the last two invalid lines. I am doing this in Eclipse.
You can try something like this.
BufferedReader reader = new BufferedReader(new FileReader(new File("~/input.csv")));
String line;
while((line = reader.readLine())!= null){
try{
int sno = Integer.parseInt( line.split(",")[0]);
System.out.println("Valid "+ line);
//Continue doing more checks or other operations
}catch(NumberFormatException e){
//Skip invalid line
System.out.println("Invalid row "+ line);
}
}
You should check by regex if is valid, throw an exception is a bad idea.
BufferedReader reader = new BufferedReader(new FileReader(new File("~/input.csv")));
String line;
while((line = reader.readLine())!= null){
if(line.matches("(\\d+,\\w+,\\d+,\\w+)"){
print line;
}
}
Something like this:
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class JavaApplication1 {
public static void main(String[] args) throws FileNotFoundException, IOException {
try (BufferedReader reader = new BufferedReader(new FileReader("file.txt"))) {
StringBuilder sb = new StringBuilder();
String line = reader.readLine();
while (line != null) {
String[] part = line.split(",");
try {
Integer.parseInt(part[0]);
System.out.println(line);
} catch (NumberFormatException nfe) {
// This is not a valid line
}
line = reader.readLine();
}
}
}
}
I'm working on a Java program in which I must read the contents of a file and then print each lines reverse. For example the text:
Public Class Helloprinter
Public static void
would print the following after running my reverse program:
retnirPolleh ssalc cilbup
diov citats cilbup
Here's what I got so far:
public static void main(String[] args) throws FileNotFoundException {
// Prompt for the input and output file names
ArrayList<String> list = new ArrayList<String>();
//String reverse = "";
Scanner console = new Scanner(System.in);
System.out.print("Input file: ");
String inputFileName = console.next();
System.out.print("Output file: ");
String outputFileName = console.next();
// Construct the Scanner and PrintWriter objects for reading and writing
File inputFile = new File(inputFileName);
Scanner in = new Scanner(inputFile);
PrintWriter out = new PrintWriter(outputFileName);
String aString = "";
while(in.hasNextLine())
{
String line = in.nextLine();
list.add(line);
}
in.close();
for(int i = 0; i <list.size(); i++)
{
aString = list.get(i);
aString = new StringBuffer(aString).reverse().toString();
out.printf("%s", " " + aString);
}
out.close();
}
}
EDIT:
With Robert's posting it helped put me in the right direction. The problem is that with that is that it doesn't keep the lines.
Public Class Helloprinter
Public static void
becomes after running my program:
retnirPolleh ssalc cilbup diov citats cilbup
it needs to keep the line layout the same. so it should be:
retnirPolleh ssalc cilbup
diov citats cilbup
Your problem is in the line
out.printf("%s", " " + aString);
This doesn't output a newline. I'm also not sure why you are sticking a space in there.
It should be either:
out.println( aString );
Or
out.printf("%s%n", aString);
In your last loop why don't you just iterate through the list backwards? So:
for(int i = 0; i <list.size(); i++)
Becomes:
for(int i = list.size() - 1; i >=0; i--)
It seems like you already know how to read a file, so then call this method for each line.
Note, this is recursion and it's probably not the most efficient but it's simple and it does what you want.
public String reverseString(final String s) {
if (s.length() == 0)
return s;
// move chahctrachter at current position and then put it at the end of the string.
return reverseString(s.substring(1)) + s.charAt(0);
}
Just use a string builder. You were on the right trail. Probably just needed a little help. There is no "one way" to do anything, but you could try something like this:
Note: Here is my output: retnirPolleh ssalc cilbup diov citats cilbup
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.Scanner;
public class Reverse {
public static void main(String[] args) {
ArrayList<String> myReverseList = null;
System.out.println("Input file: \n");
Scanner input = new Scanner(System.in);
String fileName = input.nextLine();
System.out.println("Output file: \n");
String outputFileName = input.nextLine();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader(fileName));
String text = null;
myReverseList = new ArrayList<String>();
StringBuilder sb = null;
try {
while ((text = br.readLine()) != null) {
sb = new StringBuilder();
for (int i = text.length() - 1; i >= 0; i--) {
sb.append(text.charAt(i));
}
myReverseList.add(sb.toString());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Writer writer = null;
try {
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(outputFileName), "utf-8"));
for (String s : myReverseList) {
writer.write("" + s + "\n");
}
} catch (IOException ex) {
// report
} finally {
try {
writer.close();
} catch (Exception ex) {
}
}
}
}
I have number of text files in the following format:
196903274115371008 #266093898
Prince George takes his first public steps with his mom, Catherine, Duchess of
Cambridge.
I would like to remove all extra while spaces + new line characters except the first new line characters. So I would like to above to be like this:
196903274115371008#266093898
Prince George takes his first public steps with his mom, Catherine, Duchess of Cambridge.
I wrote the following code :
package remove_white_space222;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class Remove_white_space222 {
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ");
fw.write(line);
}
fr.close();
fw.close();
}
}
Thanks in advance for your help,,,,
File file = new File("input_file.txt");
try(BufferedReader br = new BufferedReader(new FileReader(file));
FileWriter fw = new FileWriter("empty_file.txt")) {
String st;
while((st = br.readLine()) != null){
fw.write(st.replaceAll("\\s+", " ").trim().concat("\n"));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here's one approach:
public static void main(String[] args) throws IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
String line;
int lineNum = 0;
while((line = br.readLine()) != null)
{
//check if we are working with the first two lines
//(which should remain untouched)
if (lineNum > 1) {
//make sure we ignore any empty lines
if (line.trim().length() > 0) {
//add a space to the end of each line to make
//padding before we append the next line.
line=line.trim().replaceAll("\\s+", " ") + " ";
}
} else {
//remove all whitespace.
line = line.trim().replaceAll("\\s", "");
line = line + "\n";
}
fw.write(line);
lineNum++;
}
fr.close();
fw.close();
}
Output:
196903274115371008#266093898
Prince George takes his first public steps with his mom, Catherine, Duchess of Cambridge. %
You can use status via an enum to add newlines after first line and all empty lines following it.
package remove_white_space222;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.PrintWriter
import java.io.IOException;
public class Remove_white_space222 {
enum Status {
FIRST, EMPTY, NORMAL;
}
public static void main(String[] args) throws FileNotFoundException, IOException {
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt");
PrintWriter pw = new PrintWriter(fw);
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ");
fw.write(line);
if (status != Status.NORMAL) {
if ((status == Status.FIRST) || line.isEmpty()) {
pw.println();
status = Status.EMPTY;
} else {
status = Status.NORMAL;
}
}
}
fr.close();
fw.close();
}
}
You can keep your logic for all the lines but line 1 (the 2nd line), just stick "\n\n" in that case, so you have an empty line.
Also, I'd advise to open your resources in the try this way you don't have to worry about closing them
try(FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("outfile.txt") ) {
String line;
int lineNumber = 0;
while((line = br.readLine()) != null) {
if(lineNumber == 1) {
line = "\n\n";
} else {
line = line.trim().replaceAll("\\s+", " ");
}
fw.write(line);
lineNumber++;
}
}
Outputs:
196903274115371008 #266093898
Prince George takes his first public steps with his mom, Catherine, Duchess ofCambridge.
I am trying to split text files in a directory along a line 'END OF CUSTOMER STATEMENT' and I store the result files into a temporary directory. The split happens only for the first file while the other file is ignored, what is the problem with my code. I was expecting the for loop will engulf all the files in the directory? Here is my code.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
*
* #author Administrator
*/
public class SplitFiles {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
File f = new File("D:/statements/");
String[] filenames = f.list();
File[] texts = f.listFiles();
String lines = "";
for (int m = 0; m < filenames.length; m++) {
try {
int count = 0;
FileInputStream fs = new FileInputStream("D:/statements/" + filenames[m]);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileOutputStream fos = new FileOutputStream("D:/DFCU Statements/statement" + count + ".RPT");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(fos));
while ((lines = br.readLine()) != null) {
String mine = lines.trim();
if (mine.startsWith("END OF CUSTOMER STATEMENT")) {
bw.close();
count++;
fos = new FileOutputStream("D:/DFCU Statements/statement" + count + ".RPT");
bw = new BufferedWriter(new OutputStreamWriter(fos));
continue;
}
if (mine.isEmpty()) {
continue;
} else {
bw.write(lines);
bw.newLine();
bw.flush();
}
}
fos.close();
fs.close();
br.close();
bw.close();
} catch (Exception ag) {
System.out.println(ag);
}
}
}
}
I think you should do this in the first place (there are possibly more bugs)
int count = 0;
for (int m = 0; m < filenames.length; m++) {
...
UPDATE besides, remove your count++ and place it after each file creation
FileOutputStream fos = new FileOutputStream("D:/DFCU Statements/statement" + count + ".RPT");
count++;
then it will work as expected
I assume that since the target files have nothing that distinguishes them from each other (they are all named statementX.RPT) - that the last file is actually the one you have in your output - but this is only a guess.
try to change your output file to be named "statement." + m + "." + count ".RPT" and that way you will have unique output files.
Also, take note to the following comments:
When using the File class, the listFiles API is more usefull (in my opinion) - from each file you get you can query getName and getPath.
About this line: FileInputStream fs = new FileInputStream("D:/statements/" + filenames[m]); - if you used the results you got from listFiles you could replace it with FileInputStream fs = new FileInputStream(files[m]); - no need to hard-code the path.
You should modify your code. Otherwise instead of creating two output files your code will create three output files. Here is the correct code
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
/**
*
* #author Administrator
*/
public class SplitFiles {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
File f = new File("D:/statements/");
String[] filenames = f.list();
File[] texts = f.listFiles();
String lines = "";
int count = 0;
for (int m = 0; m < filenames.length; m++) {
try {
FileInputStream fs = new FileInputStream("D:/statements/" + filenames[m]);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
FileOutputStream fos = null;
BufferedWriter bw = null;
while ((lines = br.readLine()) != null) {
String mine = lines.trim();
if (mine.startsWith("END OF CUSTOMER STATEMENT")) {
if(bw!=null)
{
bw.close();
}
count++;
continue;
}
if (mine.isEmpty()) {
continue;
} else {
if(bw==null)
{
fos = new FileOutputStream("D:/DFCU Statements/statement" + count + ".RPT");
bw = new BufferedWriter(new OutputStreamWriter(fos));
}
bw.write(lines);
bw.newLine();
bw.flush();
}
}
fos.close();
fs.close();
br.close();
bw.close();
} catch (Exception ag) {
System.out.println(ag);
}
}
}
}