Remove all blank spaces and empty lines - java

How to remove all blank spaces and empty lines from a txt File using Java SE?
Input:
qwe
qweqwe
qwe
qwe
Output:
qwe
qweqwe
qwe
qwe
Thanks!

How about something like this:
FileReader fr = new FileReader("infile.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
if (!line.equals("")) // don't write out blank lines
{
fw.write(line, 0, line.length());
}
}
fr.close();
fw.close();
Note - not tested, may not be perfect syntax but gives you an idea/approach to follow.
See the following JavaDocs for reference purposes:
http://download.oracle.com/javase/7/docs/api/java/io/FileReader.html
http://download.oracle.com/javase/7/docs/api/java/io/FileWriter.html

Have a look at trim() function
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#trim()
Also, some code would be helpful...

...
Scanner scanner = new Scanner(new File("infile.txt"));
PrintStream out = new PrintStream(new File("outfile.txt"));
while(scanner.hasNextLine()){
String line = scanner.nextLine();
line = line.trim();
if(line.length() > 0)
out.println(line);
}
...

This my first time answering to a question in this site so please be understandable, after a lot of searching I have found this that works for me.
FileReader fr = new FileReader("Input_Code.txt");
BufferedReader br = new BufferedReader(fr);
FileWriter fw = new FileWriter("output_Code.txt");
String line;
while((line = br.readLine()) != null)
{
line = line.trim(); // remove leading and trailing whitespace
line=line.replaceAll("\\s+", " ").trim().concat("\n");
if (!line.equals("")) // don't write out blank lines
{
fw.write(line, 0, line.length());
}
}
fr.close();
fw.close();

Remove spaces for each line and do not consider empty and null lines:
String line = buffer.readLine();
while (line != null) {
line = removeSpaces(line);
//ignore empty lines
if (line.isEmpty()) return;
....code....
line = buffer.readLine();
}
public String removeSpaces (String arg)
{
Pattern whitespace = Pattern.compile("\\s");
Matcher matcher = whitespace.matcher(arg);
String result = "";
if (matcher.find()) {
result = matcher.replaceAll("");
}
return result;
}

Used to remove empty lines in same the file.
public static void RemoveEmptyLines(String FilePath) throws IOException
{
File inputFile = new File(FilePath);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
String inputFileReader;
ArrayList <String> DataArray = new ArrayList<String>();
while((inputFileReader=reader.readLine())!=null)
{
if(inputFileReader.length()==0)
{
continue;
}
DataArray.add(inputFileReader);
}
reader.close();
BufferedWriter bw = new BufferedWriter(new FileWriter(FilePath));
for(int i=0;i<DataArray.size();i++)
{
bw.write(DataArray.get(i));
bw.newLine();
bw.flush();
}
bw.close();
}

package com.home.interview;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class RemoveInReadFile {
public static void main(String[] args) {
try {
Scanner scanner = new Scanner(new File("Readme.txt"));
while(scanner.hasNext())
{
String line = scanner.next();
String lineAfterTrim = line.trim();
System.out.print(lineAfterTrim);
}
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

I think you just want a regex expression:
txt= txt.replaceAll("\\n\\s*\\n", "\n"); //remove empty lines
txt= txt.replaceAll("\\s*", ""); //remove whitespaces
As for reading/writing files, there are plenty of other resources to find out how to do that.

Related

Based on condition txt file divided into two files in java

My target is i have one txt file it contains some line of text. in this i have two words i.e A and 1. if line has "A" letter then next lines goto one file until next line contain "1" and if line contain "1" then next lines goto other file until "A" find.
Input file like follows
A
rahu
pahdu
jhaani
1
hjsdh
dhj
A
jiko
raju
A
tenk
kouou
I am expecting output
A.txt contain
rahu
pahdu
jhaani
Same
1.txt
My code
{
fis = new FileInputStream("E:\\Input.txt");
reader = new BufferedReader(new InputStreamReader(fis));
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while(line != null){
if(line.contains("LETTER00~VSAQCCCC~H~")) {
line = reader.readLine();
System.out.println(line);
}
else {
line= reader.readLine();
}
}
}
You could just repoint your FileOutputStream whenever you find a 1 or A.
public static void main(String[] args) throws IOException {
FileInputStream fis = new FileInputStream("in.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis));
FileOutputStream fosA = new FileOutputStream("out_A.txt");
FileOutputStream fos1 = new FileOutputStream("out_1.txt");
FileOutputStream fos = null;
System.out.println("Reading File line by line using BufferedReader");
String line = reader.readLine();
while (line != null) {
System.out.println(line);
if(line.equals("A"))
{
fos = fosA;
line = reader.readLine();
continue;
}
if(line.equals("1"))
{
fos = fos1;
line = reader.readLine();
continue;
}
fos.write(line.getBytes());
fos.write('\n');
fos.flush();
line = reader.readLine();
}
fos.close();
fosA.close();
fos1.close();
}
You can do something like this.
System.out.println("Reading File line by line using
BufferedReader");
String inputFIle = "";
String line;
boolean flag = false;
// String line = reader.readLine();
while ((line = reader.readLine()) != null) {
if (line.trim().equalsIgnoreCase("A")) {
inputFIle = "A.txt";
} else if(line.trim().equalsIgnoreCase("1")){
inputFIle = "1.txt";
}
else{
write(line, inputFIle);
}
}
You can do something like this
public static void main(String[] args) throws IOException {
Scanner scanner = new Scanner(new FileReader("Input.txt"));
boolean isFound = false;
List<String> main_list = new ArrayList<>();
List<String> sub_list = new ArrayList<>();
while(scanner.hasNextLine()){
String line = scanner.nextLine();
if(line.contains("A")) {
isFound = true;
} else if(line.contains("1")) {
isFound = false;
for (String aSub_list : sub_list) {
main_list.add(aSub_list);
}
sub_list.clear();
}
if(isFound && !line.contains("A")) {
sub_list.add(line);
}
}
for (String aMain_list : main_list) {
System.out.println(aMain_list);
}
}

Write to a specific line in a txt document java

I know that there are already some posts about this problem but I don't understand them.
My problem is that I want to find a line in a txt document with a name and I then want to change the next line to the content of a string.
This is what I tried:
public void saveDocument(String name) {
String documentToSave = textArea1.getText();
File file = new File("documents.txt");
Scanner scanner;
BufferedWriter bw;
try {
scanner = new Scanner(file);
bw = new BufferedWriter(new FileWriter(file));
while(scanner.hasNextLine()) {
if(scanner.nextLine().equals(name)) {
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
bw.write(documentToSave + "\n");
if(scanner.hasNextLine()) scanner.nextLine();
}
if(scanner.hasNextLine()) bw.write(scanner.nextLine() + "\n");
}
bw.flush();
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
May be you try it this way: read your file and keep each line in a list of strings and if you find the name you are looking for replace the next line you read. And then write the strings from that list back to your file. Example:
public class NewClass {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list = readFile("uzochi");
writeToFile(list);
}
public static List<String> readFile(String name){
List<String> list = new ArrayList<String>();
try {
FileReader reader = new FileReader("C:\\users\\uzochi\\desktop\\txt.txt");
BufferedReader bufferedReader = new BufferedReader(reader);
String line;
boolean nameFound = false;
while ((line = bufferedReader.readLine()) != null) {
if(line.equalsIgnoreCase(name)){
nameFound = true;
System.out.println("searched name: "+line);
}
if(nameFound){
list.add(line);
line = bufferedReader.readLine();
System.out.println("line to replace: " + line);
line = "another string";
System.out.println("replaced line: "+line);
list.add(line);
nameFound = false;
}
else{
list.add(line);
}
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
return list;
}
public static void writeToFile(List<String> list){
try {
FileWriter writer = new FileWriter("C:\\users\\uzochi\\desktop\\txt.txt", false);
BufferedWriter bufferedWriter = new BufferedWriter(writer);
for(String s: list){
bufferedWriter.write(s);
bufferedWriter.newLine();
}
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
txt.txt
hallo
hello
hola
uzochi
world
java
print
This code should read the entire file and replace the line with the name.
while(scanner.hasNextLine()) {
String line = scanner.nextLine();
if(line.equals(name)) {
bw.write(documentToSave + "\n");
} else {
bw.write(line + "\n");
}
}
This program will replace the line after a given line. It needs some more work from us, for example if we can define expected i/o and usage. Now it reads from a file and reeplaces a line, but maybe you want to use the line number instead of the line contents to mark which line to replace.
import java.io.*;
public class FileLineReplace {
public static void replaceSelected(String replaceWith, String type) {
try {
String input2 = "";
boolean replace = false;
String input = "";
try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
for (String line;
(line = br.readLine()) != null;) {
// process the line.
System.out.println(line); // check that it's inputted right
if (replace) {
line = "*** REPLACED ***";
replace = false;
}
if (line.indexOf("replaceNextLine") > -1) {
replace = true;
}
input2 = input2 += (line + "\n");
}
// line is not visible here.
}
// check if the new input is right
System.out.println("----------------------------------" + '\n' + input2);
// write the new String with the replaced line OVER the same file
FileOutputStream fileOut = new FileOutputStream("data.txt");
fileOut.write(input2.getBytes());
fileOut.close();
} catch (Exception e) {
System.out.println("Problem reading file.");
e.printStackTrace();
}
}
public static void main(String[] args) {
replaceSelected("1 adam 20 M", "foobar");
}
}
If you run the code, it will replace next line after a line which is "replaceNextLine":
$ java FileLineReplace
asd
zxc
xcv
replaceNextLine
wer
qwe
----------------------------------
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe
My test file is (was)
asd
zxc
xcv
replaceNextLine
wer
qwe
After I run the program, the file looks like this and the line after the specified line is replaced.
asd
zxc
xcv
replaceNextLine
*** REPLACED ***
qwe

I need to print all words that start with the letter "*" in to another output txt (13000 lines) but this program works with like 200 or so

private static void readFile1(String in, String out) throws IOException
{
FileInputStream fis = new FileInputStream(new File(in));
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
BufferedWriter writer = null;
writer = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(out), "utf-8"));
String line = null;
while ((line = br.readLine()) != null)
{
if(line.length() > 0)
{
String[] words = line.split("\\s+");
for(String word : words)
{
if(word.charAt(0)=='*')
{
//System.out.println(word);
writer.write(word);
writer.newLine();
}
}
}
}
br.close();
writer.close();
fis.close();
}
}
Can someone help me with this one?
In cmd i get something like "Exception in thread "main" java.lang.StringIndexOutOfBoundsException:String index out of range:0
The only place you seem to be referencing an index on a string is this if-statement:
if(word.charAt(0)=='*')
Change your if statement to be:
if(!word.isEmpty() && word.charAt(0)=='*')
This will first check if the word is empty and if it is not, then it will look for the proper char
UPDATE
You should add in a NULL check on word as well, just to avoid a NullPointerException
if(word != null && !word.isEmpty() && word.charAt(0)=='*')

How to read records from a text file?

I tried this:
public static void ReadRecord()
{
String line = null;
try
{
FileReader fr = new FileReader("input.txt");
BufferedReader br = new BufferedReader(fr);
line = br.readLine();
while(line != null)
{
System.out.println(line);
}
br.close();
fr.close();
}
catch (Exception e)
{
}
}
}
It non stop and repeatedly reads only one record that i had inputtd and wrote into the file earlier...How do i read records and use tokenization in reading records?
You have to read the lines in the file repeatedly in the loop using br.readLine(). br.readLine() reads only one line at time.
do something like this:
while((line = br.readLine()) != null) {
System.out.println(line);
}
Check this link also if you have some problems. http://www.mkyong.com/java/how-to-read-file-from-java-bufferedreader-example/
Tokenization
If you want to split your string into tokens you can use the StringTokenizer class or can use the String.split() method.
StringTokenizer Class
StringTokenizer st = new StringTokenizer(line);
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
st.hasMoreTokens() - will check whether any more tokens are present.
st.nextToken() - will get the next token
String.split()
String[] result = line.split("\\s"); // split line into tokens
for (int x=0; x<result.length; x++) {
System.out.println(result[x]);
}
line.split("\\s") - will split line with space as the delimiter. It returns a String array.
try this
while((line = br.readLine()) != null)
{
System.out.println(line);
}
Try This :
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
while((line=br.readline())!=null)
System.out.println(line);
For a text file called access.txt locate for example on your X drive, this should work.
public static void readRecordFromTextFile throws FileNotFoundException
{
try {
File file = new File("X:\\access.txt");
Scanner sc = new Scanner(file);
sc.useDelimiter(",|\r\n");
System.out.println(sc.next());
while (sc.hasNext()) {
System.out.println(sc.next());
}
sc.close();// closing the scanner stream
} catch (FileNotFoundException e) {
System.out.println("Enter existing file name");
e.printStackTrace();
}
}

How can i split a textfile and store 2 values in one line?

I have a text file -> 23/34 <- and I'm working on a Java program.
I want to store them out in String One = 23 and anotherString = 34 and put them together to one string to write them down in a text file, but it dosen't work. :( Everytime it makes a break. Maybe because the split method but I don't know how to separate them.
try {
BufferedReader in = new BufferedReader (new FileReader (textfile) );
try {
while( (textfile= in.readLine()) != null ) {
String[] parts = textfileString.split("/");
String one = parts[0];
}
}
}
When I print or store one + "/" + anotherString, it makes a line-break at one but I want it all in one line. :(
public static void main(String[] args) throws Exception {
File file = new File("output.txt");
if (!file.exists()) {
file.createNewFile();
}
BufferedWriter bw = new BufferedWriter(new FileWriter(file.getAbsoluteFile()));
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
String line = null;
while ((line = br.readLine()) != null) {
String string1 = line.split("/")[0];
String string2 = line.split("/")[1];
bw.write(string1 + string2 + "\n");
bw.flush();
}
br.close();
bw.close();
}
On file:
23/34
Resulted in output.txt containing:
2334
You need to read in each line, and split it on your designated character ("/"). Then assign string1 to the first split, and string2 to the second split. You can then do with the variables as you want. To output them to a file, you simply append them together with a + operator.
You have never shown us how you are writing the file, so we can't really help you with your code. This is a bit of a more modern approach, but I think it does what you want.
File infile = new File("input.txt");
File outfile = new File("output.txt");
try (BufferedReader reader = Files.newBufferedReader(infile.toPath());
BufferedWriter writer = Files.newBufferedWriter(outfile.toPath())) {
String line;
while ((line = reader.readLine()) != null) {
String parts[] = line.split("/");
String one = parts[0];
String two = parts[1];
writer.write(one + "/" + two);
}
} catch (IOException ex) {
System.err.println(ex.getLocalizedMessage());
}
InputStream stream = this.getClass().getResourceAsStream("./test.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String currentLine;
try {
while ((currentLine = reader.readLine()) != null) {
String[] parts = currentLine.split("/");
System.out.println(parts[0] + "/" + parts[1]);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}

Categories