android remove known line from txt file - java

I need to remove one line from txt file and I already know the position of this line.
I know how to replace data on txt file reading whole content but I would like to delete line from specific position. Thank you.
BufferedReader br = new BufferedReader(new FileReader("data/data/"+ PACKAGE_NAME +"/myFile.txt"));
//delete Line on position 2 (as example)
br.close();

You could read all of the lines from the File first and store them in a List<String>. Then you could remove the index and write back all of the lines. Perhaps it might look something like:
public void removeLine(final File file, final int lineIndex) throws IOException{
final List<String> lines = new LinkedList<>();
final Scanner reader = new Scanner(new FileInputStream(file), "UTF-8");
while(reader.hasNextLine())
lines.add(reader.nextLine());
reader.close();
assert lineIndex >= 0 && lineIndex <= lines.size() - 1;
lines.remove(lineIndex);
final BufferedWriter writer = new BufferedWriter(new FileWriter(file, false));
for(final String line : lines)
writer.write(line);
writer.flush();
writer.close();
}
Usage:
public static void main(String args[]) throws IOException{
final File file = ...;
removeLine(file, 2);
}
The code above will remove the 3rd line.

by jni, use
open
mmap
memcpy
munmap
ftruncate
close

Related

Writing per line new CSV File (JAVA)

I have the following code:
public static void main(String[] args) throws IOException {
//File being read:
String fileName = "src/data/Belgium.csv";
String[] nextLine;
try (CSVReader reader = new CSVReader(new FileReader(fileName), ',', '"', 1)) {
while ((nextLine = reader.readNext()) != null) {
for (String line : nextLine) {
//NewFile
//When 2nd parameter - ture, it gets so big, that excel can't handle it anymore...
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);
line = line.replaceAll("T", " ");
line = line.replaceAll("Z", "");
line = line.replaceAll("ActualGenerationPerUnit.mean", "");
line = line.replaceAll("Plantname:", "");
//Escaping curly braces is a must!
line = line.replaceAll("\\{", "");
line = line.replaceAll("\\}", "");
writer.append(line);
writer.flush();
writer.close();
System.out.println(line);
}
}System.out.println("Successfully written");
}
}
The output of the code in my console, using System.out.println(line) gives me the correct output.
However, when I open the CSV file, it seems like it is written reversed.
Excel first complains about the amount of rows.
However, only the last row of my original dataset shows.
The dataset (which is preprocessed in an inefficient way), contains more than 1000 rows. Therefore, I can not simply append every single entry.
Is there a better way of doing this?
Tips and tricks are very welcome.
Furtermore, I have tried several writers:
- CSVwrite
- BufferedWriter
- FileWriter
Also checked other issues on Stackoverflow...
Can't seem to make it work. Thank you!
UPDATE:
Question is answered! Final code:
public static void main(String[] args) throws IOException {
//File being read:
String fileName = "src/data/Belgium.csv";
//When 2nd parameter - ture, it gets so big, that excel can't handle it anymore...
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew5.csv", true);
String[] nextLine;
try (CSVReader reader = new CSVReader(new FileReader(fileName), ',', '"', 1)) {
while ((nextLine = reader.readNext()) != null) {
for (String line : nextLine) {
line = line.replaceAll("T", " ");
line = line.replaceAll("Z", "");
line = line.replaceAll("ActualGenerationPerUnit.mean", "");
line = line.replaceAll("Plantname:", "");
//Escaping curly braces is a must!
line = line.replaceAll("\\{", "");
line = line.replaceAll("\\}", "");
writer.append(line);
writer.append(System.lineSeparator());
System.out.println(line);
}
}System.out.println("Successfully written");
}catch(Exception e){
e.printStackTrace();
}finally {
if (writer != null){
writer.flush();
writer.close();
}
}
}
However, when I open the CSV file, it seems like it is written
reversed. Excel first complains about the amount of rows. However,
only the last row of my original dataset shows.
I think that it is probably caused because a new line character between CSV rows is missing.
Actually you don't write a new line character when you write a row in the file.
You could write it : writer.append(System.lineSeparator()) after each read line.
As side notes :
1) Why not moving it before the loop (otherwise it is less efficient) :
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);
2) You should not flush and close the file at each read line as it is less efficient :
writer.append(line);
writer.flush();
writer.close();
System.out.println(line);
It should be enough :
writer.append(line);
System.out.println(line);
Keep that :
writer.flush();
writer.close();
in a finally statement such as :
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);
try{
// all your operations to handle the file
}
catch(Exception e){
// your exception handling
}
finally{
if (writer!=null){
writer.flush();
writer.close();
}
}
EDIT to answer to the comment :
If you have the impression that the output file contains multiple set of records, it is probably related to the append mode of the FileWriter that you used.
Replace that :
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", true);
by this to not use this mode :
FileWriter writer = new FileWriter("src/dataNew/BelgiumNew1.csv", false);
I see you are using opencsv to read your csv file. In addition to the correct answer from davidxxx you could simplyfy your code if you use the CSVWriter from opencsv to write to file. Below is an example:
import com.opencsv.CSVReader;
import com.opencsv.CSVWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
public class Example1 {
public static void main(String args[]) throws IOException {
String fileName = "src/data/Belgium.csv";
CSVReader reader = new CSVReader(new FileReader(fileName), ',','"',1);
List<String[]> lines = reader.readAll();
CSVWriter writer = new CSVWriter(new FileWriter("src/data/BelgiumNew1.csv",false), ',');
for(String[] row : lines){
for(int i = 0; i< row.length; i++){
row[i] = row[i].replaceAll("T", " ")
.replaceAll("Z", "z")
.replaceAll("ActualGenerationPerUnit.mean", "")
.replaceAll("Plantname:", "")
.replaceAll("\\{", "")
.replaceAll("\\}", "");
}
writer.writeNext(row);
}
writer.flush();
writer.close();
}
}

Converting a .java file to a .txt document

I am trying to figure out how to load a .java doc and out put it into a text document...
What needs to be done:
Write a program that opens a Java source file, adds line numbers, and
saves the result in a new file. Line numbers are numbers which
indicate the different lines of a source file, they are useful when
trying to draw someone's attention to a particular line (e.g.,
"there's a bug on line 4"). Your program should prompt the user to
enter a filename, open it, and then save each line to an output fix
with the line numbers prepended to the beginning of each line.
Afterward, display the name of the output file. The name of the output
file should based on the input file with the '.' replaced by a '_',
and ".txt" added to the end. (Hint: if you are using a PrintWriter
object called pw to save the text file, then the line
"pw.printf("%03d", x);" will display an integer x padded to three
digits with leading zeros.)
The text.java needs to output into the text document with numbered lines such as:
001 public class dogHouse {
002 public static void main (String[] args) {
003 and so on...
004
import java.io.*;
public class dogHouse {
public static void main(String [] args) throws IOException {
// The name of the file to open.
String fileName = "test.java";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
// The name of the file to open.
finally {
// Assume default encoding.
FileWriter fileWriter =
new FileWriter(fileName);
// Always wrap FileWriter in BufferedWriter.
BufferedWriter bufferedWriter =
new BufferedWriter(fileWriter);
// Note that write() does not automatically
// append a newline character.
bufferedWriter.write("Hello there,");
// Always close files.
bufferedWriter.close();
}
}
}
You need to print and count the line(s) as you read them. You also need to differentiate between your output file and your input file. And, I would prefer to use try-with-resources Statements. Something like,
String fileName = "test.java";
String outputFileName = String.format("%s.txt", fileName.replace('.', '_'));
try (BufferedReader br = new BufferedReader(new FileReader(fileName));
PrintWriter pw = new PrintWriter(new FileWriter(outputFileName))) {
int count = 1;
String line;
while ((line = br.readLine()) != null) {
pw.printf("%03d %s%n", count, line);
count++;
}
} catch (Exception e) {
e.printStackTrace();
}

How to replace both int and string

I have a String like "HelloWorld!9090Hello" in a file, and i want to replace the whole string with a new One, Tried this but didn't helped
Example File abc.txt:
a=HelloWorld!9090Hello
String neww = "abcdef";
File file = new File("abc.txt");
File wr = new File("tmp.txt");
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
// tried even line.toString();//
String rline= line.replace("HelloWorld!9090Hello", neww);
BufferWrite(rline,wr);
}
br.close();
public static void BufferWrite(String St,File file) throws IOException{
FileWriter fw = new FileWriter(file.getAbsoluteFile(),true);
BufferedWriter bw = new BufferedWriter(fw);
bw.write(St);
bw.write("\r\n");
bw.close();
}
The BufferWrite() writes text to the tmp.txt file..
Result :
a=HelloWorld!9090Hello
I ran your exact code in Eclipse, and it creates the tmp file correctly for me and it has "abcdef" in it.
Did you make sure you actually started with exactly "HelloWorld!9090Hello" in your input file? It looks like you are starting with "a=HelloWorld!9090Hello", not "HelloWorld!9090Hello". The replace function will only work when the Strings are an exact match. If you're starting with "a=HelloWorld!9090Hello", change the replace function to the following:
String rline= line.replace("a=HelloWorld!9090Hello", neww);

How to handle ArrayIndexedBoundexception in Java

I have been trying to get a specific columns from a csv file say having 30 columns but i need only 3 columns entirely when i execute the following code only i get only one entire column data..how to get 3 column data at a time.when i run it prints only one column...when i try to print multiple column it shows error message like
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at ReadCVS.main(ReadCVS.java:19)
public static void main(String[] args) throws Exception {
String splitBy = ",";
BufferedReader br = new BufferedReader(new FileReader("txt.csv"));
String line = br.readLine();
while((line = br.readLine()) !=null){
String[] b = line.split(splitBy);
PrintWriter out = new PrintWriter(new FileWriter("new.csv",true));
out.println(b[0]);
out.close();
}
br.close();
}
The problem is probably is:
You have only one line in your, txt.csv file.
When you called br.readLine(); for the first time, that line is read from the file and stored in String line variable. But you ignored that line, and you've read again, in your while condition:
while((line = br.readLine()) !=null)
So maybe you have an empty line or empty string after that first line. Then the while condition is true, but an empty String is stored in line variable. So the b[] has no element and b[0] is out of the bound.
One solution is to change this line:
String line = br.readLine();
to
String line = null;
[EDIT]
So if you try to read a file like the one in mkyong's site (as you linked in your comment) and split the lines by "," and write them in a new file for example, you can use a code like the code below:
public static void main(String[] args) throws IOException {
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
BufferedReader br = new BufferedReader(new FileReader("c:\\txt.csv"));
String splitBy = ",";
String line = null;
while((line = br.readLine()) !=null){
StringBuffer newLine = new StringBuffer();
String[] b = line.split(splitBy);
for (int i = 0; i<b.length; i++)
{
if(b[i] == null || b[i].trim().isEmpty())
continue;
newLine.append(b[i].trim() + ";");
}
out.write(newLine.toString());
out.newLine();
}
out.close();
br.close();
}
Also you should know that the following line opens the output file in appendable way(the second boolean parameter in the constructor):
BufferedWriter out = new BufferedWriter(new FileWriter("c:\\new.csv",true));
Also I assumed the contents of the source file is the same as in mkyong's site, somethimg like this:
"1.0.0.0",, , ,"1.0.0.255","16777216", , "16777471","AU" ,, "Australia"
"1.0.1.0" , ,, "1.0.3.255" ,, ,"16777472","16778239" , , "CN" , ,"China"
"1.0.4.0","1.0.7.255","16778240","16779263","AU","Australia"
"1.0.8.0","1.0.15.255","16779264","16781311","CN","China"
"1.0.16.0","1.0.31.255","16781312","16785407","JP","Japan"
"1.0.32.0","1.0.63.255","16785408","16793599","CN","China"
"1.0.64.0","1.0.127.255","16793600","16809983","JP","Japan"
"1.0.128.0","1.0.255.255","16809984","16842751","TH","Thailand"
Good Luck.

read from file and write some parts in another file

I have to read from a text file and format the input. I'm new to java reading from files, and I don't know how to work with just some parts of what I read
Here is the initial file: http://pastebin.com/D0paWtAd
And I have to write in another file the following output:
Average,Joe,44,31,18,12,9,10
I've managed just to take everything from the file and print it to output. I would need help just in taking the output I need and print it to the screen. Any help is appreciated.
This is what I wrote up to now:
public class FileParsing {
public static String
read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader("C:\\Users\\Bogdi\\Desktop\\example.txt"));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) sb.append(s + "\n");
in.close();
return sb.toString();
}
If your goal is to do the specified output in another file you don't need to first get the content of your file in a StringBuilder before processing it, you can append the processed datas directly in a StringBuilder then you can write the result in a file. Here is an example that would work for the given file but you may have to modify it if the keys change in the future:
The following method will correctly process the datas from your file
public static String read(String filename) throws IOException {
BufferedReader in = new BufferedReader(new FileReader(filename));
String s;
StringBuilder sb = new StringBuilder();
while((s = in.readLine())!= null) {
String[] split1 = s.split("=");
if (split1[0].equals("name")) {
StringTokenizer tokenizer = new StringTokenizer(split1[1]);
sb.append(tokenizer.nextToken());
sb.append(",");
sb.append(tokenizer.nextToken());
sb.append(",");
} else if (split1[0].equals("index")) {
sb.append(split1[1] + ",");
} else if (split1[0].equals("FBid")) {
sb.append(split1[1]);
} else {
StringTokenizer tokenizer = new StringTokenizer(split1[1]);
String wasted = tokenizer.nextToken();
sb.append(tokenizer.nextToken() + ",");
}
}
in.close();
return sb.toString();
}
The next method will read any string to a file
public static void writeStringToFile(String string, String filePath) throws IOException {
BufferedWriter writer = new BufferedWriter(
new FileWriter(
new File(filePath)
)
);
writer.write(string);
writer.newLine();
writer.flush();
writer.close();
}
And here is a simple tests (File1.txt contains the datas from the file you shared on paste bin and I write them in another file)
public static void main(String[] args) throws Exception {
String datas = read("C:\\Tests\\File1.txt");
System.out.println(datas);
writeStringToFile(datas, "C:\\Tests\\FileOuput.txt" );
}
It will produce the exact output that you are expecting
[EDIT] #idk, apparently you have an exception executing my example, while it is working fine for me. That could only mean there is an error at data level. Here is the data sample that I used (and I believe I exactly copy the datas you shared)
And here is the result:
Good to know you are using "StringBuilder" component instead being concatenating your String values, way to go :).
More than knowledge on the Java.IO API to work with files, you will need some logic to get the results you expect. Here I came with an approach that could help you, not perfect, but can point you on how to face this problem.
//Reference to your file
String myFilePath = "c:/dev/myFile.txt";
File myFile = new File(myFilePath);
//Create a buffered reader, which is a good start
BufferedReader breader = new BufferedReader(new FileReader(myFile));
//Define this variable called line that will evaluate each line of our file
String line = null;
//I will use a StringBuilder to append the information I need
StringBuilder appender = new StringBuilder();
while ((line = breader.readLine()) != null) {
//First, I will obtain the characters after "equals" sign
String afterEquals = line.substring(line.indexOf("=") + 1, line.length());
//Then, if it contains digits...
if (afterEquals.matches(".*\\d+.*")) {
//I will just get the digits from the line
afterEquals = afterEquals.replaceAll("\\D+","");
}
//Finally, append the contents
appender.append(afterEquals);
appender.append(",");//This is the comma you want to include
}
//I will delete the last comma
appender.deleteCharAt(appender.length() - 1);
//Close the reader...
breader.close();
//Then create a process to write the content
BufferedWriter myWriter = new BufferedWriter(new FileWriter(new File("myResultFile.txt")));
//Write the full contents I get from my appender :)
myWriter.write(appender.toString());
//Close the writer
myWriter.close();
}
Hope this can help you. Happy coding!

Categories

Resources