Java: deleting text in an csv which starts with -- - java

I am loading a csv file and kept alive without closing BufferReader. Now I want to delete all lines which starts with -- and save that csv in a temp CSV. Anybody have an idea how I can do this find only c# code.
I tried to fix with regular expression but I failed.
An example of the csv:
-- DDL- "T453453 "."BMG"
-- DDL- "T423342 "."BMG234"
CREATE TABLE "T453453 "."BMG"
-- DDL- "T42234234 "."BMG236"
So it works but i have the last problem how i can add \n (Newline) cause if i debug this code i get the text in one line.
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
public class CsV {
public static String Read() throws IOException{
return new String(Files.readAllBytes(Paths.get("C://Users//myd//Desktop//BW//BWFormated.csv")));
}
public static void main(String[] args) throws IOException {
File inputFile = new File("C://Users//myd//Desktop//BW//BWtest.csv");
File tempFile = new File("C://Users//myd//Desktop//BW//BWFormated.csv");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "--";
String currentLine;
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write(currentLine);
}
writer.close();
boolean successful = tempFile.renameTo(inputFile);
System.out.println(Read());
}
}

You can check each line, if it begins with -- using String.startsWith() method.
If so, read the next line and if the line has content you want to make other things with, you can put it into a list. Maybe like this:
String line;
List<String> list = new ArrayList<String>();
while((line = reader.readLine()) != null)
{
if(line.startsWith("--"))
continue;
list.add(line);
}
for(int i = 0; i < list.length; i++)
{
line = list.get(i);
// use regular expressions to extract the data you want to convert into CSV format
}
Hint: I didn't check my syntax, so it could be, that it won't be compiled ;-)
Use the Pattern class for regular expressions and maybe this tutorial will help you.
Good luck!
EDIT
Extend your while-loop to the following, which allows you to add new lines, too:
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove))
continue;
writer.write(currentLine);
writer.newLine(); // Writes a line separator.
}
Read the docs to the newLine() method.

Related

When there are multiple lines in my file, my code works with out any error but when there's a single line,it fails

My input text file is :-
kiShore,kUMar,bhAvanam
My output file must be:-
Kishore,Kumar,Reddy
Simply my code needs to capitalize the 1st letters in file
and This is my code
public static void main(String[] args) throws Exception {
// write your code here
BufferedReader br = new BufferedReader(new FileReader("input.txt"));
FileWriter fw = new FileWriter("output.txt");
String line;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
String msg = str.substring(0, 1).toUpperCase() + str.substring(1).toLowerCase();
br.mark(0);
if (br.read()!= -1)
{
msg=msg+",";
br.reset();
}
fw.write(msg);
}
}
fw.close();
br.close();
}
My code Works perfectly when file contains multiple lines like:
kIshore,kUMar
rEdDy
i get the exact output
Kishore,Kumar,Reddy
but if my Input file contains only a single line like:
kiShore,kUMar,bhAvanam
I get the output KishoreKumarBhavanam.
I'm unable to insert commas in between words, if the input file contains only a single line
Expected result:
Kishore,kumar,Bhavanam
actual result:
KishoreKumarReddy
As per your code, the problem is you are only adding comma, when your buffered reader can read next character. But, the problem is since you have already read the whole line, there is no additional data to be read. Now, since there is nothing to read, the br.read() function call would return -1 and comma would not be added into your output.
You may observe the same behavior for multi-line file as well, where for the last line of input, the commas are not added.
To fix this, instead on relying on br.read() function, use index while looping and add comma, incase the item is not the last element in the list or use StringJoiner
I think you could do something like this:
import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.StringJoiner;
// ...
InputStream inputStream = ParseFile.class.getResourceAsStream("/input.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
FileWriter fw = new FileWriter("output.txt");
String line;
StringJoiner stringJoiner = new StringJoiner(",");
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
for (String str : values) {
stringJoiner.add(str.trim());
}
}
fw.write(stringJoiner.toString());
fw.close();
br.close();

When deleting data from a file, temp file won't rename back to original file

I am trying to remove a line based on user input. myFile.txt looks like:
Matt
Brian
John
However when I enter "Brian" (to remove this line), It is deleted on the temp file (myTempFile.txt), but not renamed back to the original file (myFile). Why is this? Thanks
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class testcode {
public static void main(String[] args) throws IOException {
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
Scanner myScan = new Scanner(System.in);
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
System.out.print("Please enter student first name: ");
String lineToRemove = myScan.nextLine();
String currentLine;
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
tempFile.renameTo(inputFile);
}
writer.close();
reader.close();
myScan.close();
}
}
Your original file is open that's why it's not working.
I suggest to do the renameTo(...) after the while and put a reader.close(); before it. It makes no sense to rename it at each readLine() of your original file. Do the processing, then rename the temporary file.
Like:
while((currentLine = reader.readLine()) != null)
{
String trimmedLine = currentLine.trim();
if(!trimmedLine.contains(lineToRemove)) {
writer.write(trimmedLine);
writer.newLine();
}
}
reader.close();
writer.close();
inputFile.delete(); //Added to my original post.
tempFile.renameTo(inputFile);
See as example: http://www.tutorialspoint.com/java/io/file_renameto.htm
After some research, I saw this: http://www.coderanch.com/t/595269/java-io/java/doesn-File-renameTo-work. If the file does exist, the renaming will not work. Try to Delete the inputFile before renaming.

Counting number of lines in .txt file Java

Hey I have problem with this simple program:
package werd;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
public class Werd {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws FileNotFoundException, IOException {
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream("ikso.txt"), "UTF-8"));
String line;
String[] tmp = null;
int slowa = 0;
int lines = 0;
while ((line = in.readLine())!= null){
lines++;
tmp = line.split("\\s");
System.out.println(line);
//System.out.println(line);
for(String s : tmp){
slowa++;
}
}
in.close();
System.out.println("Liczba wierszy to " +line+" a liczba slow w tekscie to " + slowa)
}
}
Problem is that the variable counting is not increasing. Moreover Netbeans telling me that variable limits is not used. I had glanced at similar questions as min on this page. Way of solving counting number of lines was similar to mine. I don't understand why it doesn't work...
Thanks
From the code you provided it seems you're printing line instead of lines.
The counting code looks correct.

how to use String method inside while loop

i am trying to use String method inside while loop so i can read part of the file the code is this
package AnimeAid;
import java.io.*;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class ReadFile {
public void getFileInformation() throws IOException {
try{
String file;
file = "tra.srt";
Charset charset = Charset.defaultCharset();
Path path = Paths.get(file);
BufferedReader reader = Files.newBufferedReader(path, charset);
System.out.printf("Lines from %s:%n",file);
String line;
int num = 5;
while((line = reader.readLine()) != null && line.indexOf(':') != -1){
System.out.println(line.substring(0, 10));
}
}catch(FileNotFoundException ex){
System.err.println(ex);
}
}
}
now it not give me any error message but it is not giving the right answer and i need to use return not system.out.print
Lines from tra.srt:
BUILD SUCCESSFUL (total time: 0 seconds)
how file look like
1
00:00:01,600 --> 00:00:04,080
<b>Mr Magnussen, please state your
full name for the record.</b>
2
00:00:04,080 --> 00:00:07,040
Charles Augustus Magnussen.
the output most be the timing 00:00:01,600 from every line how he know by looking for every : sign
line.indexOf(':')
returns an integer. This means you have while (boolean && int) which makes no sense in a Java world. You should compare the result of the indexOf method in order to get there a boolean as well.
Eg:
while((line = reader.readLine()) != null && line.indexOf(':') != -1)

Returning values from a text file as Strings

Okay, so I've seen a few questions about this, but the answers were a bit overwhelming and quite varied. Obviously I'm looking for the simplest solution, but a want to be able to read in lines from a text file as strings and store them in an array list. I have an addItem(String item) method for each thing that would be imported to add it to the array list, but I don't know how to import the file correctly and have each line as an individual string.
You're looking for something like BufferedReader, which has functions for reading input from a file line by line.
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
public static void main(String[] args) {
try {
FileInputStream in = new FileInputStream("inputFile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while((strLine = br.readLine())!= null) {
addItem(strLine);
}
} catch(Exception e) {
System.out.println(e);
}
}
I'm not at my computer so I didn't compile this answer but I believe you are looking for somehing like this:
// file is your txt file.
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// process the line, i.e, add to your list
}
br.close();
Hope it helps

Categories