I have a text file which has a format like this:
ab
cd
ef
gh
ij
..
I want to erase Strings after "ef", I mean after running my program the text file structure be like this:
ab
cd
ef
I'm using netbeans IDE and using java codes. Could any one help?
It's my tried code but it just keeps Strings before "ef" in a String, but I have no idea how to do the else!
BufferedReader br = new BufferedReader(new FileReader("E:\\info.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (!(line.equals("ef"))) {
sb.append(line);
// sb.append(System.lineSeparator());
line = br.readLine();
}
String everything = sb.toString();
System.out.print(everything);
// System.out.print(sb);
} finally {
br.close();
}
Here is an example to correct your file
final String fileName = "E:\\info.txt";
String everything = "";
try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (!(line.equals("ef"))) {
sb.append(line).append("\n");
// sb.append(System.lineSeparator());
line = br.readLine();
}
sb.append(line);
everything = sb.toString();
System.out.print(everything);
}
final File file = new File(fileName);
file.delete();
try (FileWriter writer = new FileWriter(fileName)) {
writer.write(everything);
}
You could use Apache commons-io's FileUtils like in the following example:
private final String FILE_NAME = "E:\\info.txt";
public void test() throws IOException {
File file = new File(FILE_NAME);
List<String> strings = FileUtils.readLines(file);
int ef = strings.indexOf("ef");
List<String> stringBeforeEF = strings.subList(0, ef);
FileUtils.writeLines(file, stringBeforeEF);
}
Related
The code below only brings up the first line of code and stops. I would like to return each line of code until there are no more.
private String GetPhoneAddress() {
File directory = Environment.getExternalStorageDirectory();
File myFile = new File(directory, "mythoughtlog.txt");
//File file = new File(Environment.getExternalStorageDirectory() + "mythoughtlog.txt");
if (!myFile.exists()){
String line = "Need to add smth";
return line;
}
String line = null;
//Read text from file
//StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(myFile));
line = br.readLine();
}
catch (IOException e) {
//You'll need to add proper error handling here
}
return line;
}
You could loop over the results of readLine() and accumulate them until you get a null, indicating the end of the file (BTW, note that your snippet neglected to close the reader. A try-with-resource structure could handle that):
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
String line = br.readLine();
if (line == null) {
return null;
}
StringBuilder retVal = new StringBuilder(line);
line = br.readLine();
while (line != null) {
retVal.append(System.lineSeparator()).append(line);
line = br.readLine();
}
return retVal.toString();
}
if you're using Java 8, you can save a lot of this boiler-plated code with the newly introduced lines() method:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
return br.lines().collect(Collectors.joining(System.lineSeparator()));
}
A considerably less verbose solution:
try (BufferedReader br = new BufferedReader(new FileReader(myFile))) {
StringBuilder retVal = new StringBuilder();
while ((line = br.readLine()) != null) {
retVal.append(line).append(System.lineSeparator());
}
return retVal.toString();
}
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();
}
}
I was working a little bit with config files and file reader classes in java.
I always read/wrote in the files with arrays because I was working with objects.
This looked a little bit like this:
public void loadUserData(ArrayList<User> arraylist) {
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
String[] userParams = line.split(";");
String name = userParams[0];
String number= userParams[1];
String mail = userParams[2];
arraylist.add(new User(name, number, mail));
}
} catch (IOException e) {
e.printStackTrace();
}
}
This works fine, but how can I save the content of a file as only one single string?
When I read a file, the string I use should be the exact same as the content of the file (without the use of arrays or line splits).
how can I do that?
Edit:
I try to read a SQL-Statement out of a file to use it with JDBC later on. That's why I need the content of the File as a single String
This method will work
public static void readFromFile() throws Exception{
FileReader fIn = new FileReader("D:\\Test.txt");
BufferedReader br = new BufferedReader(fIn);
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
String text = sb.toString();
System.out.println(text);
}
I hope this is what you need:
public void loadUserData(ArrayList<User> arraylist) {
StringBuilder sb = new StringBuilder();
try {
List<String> lines = Files.readAllLines(path, Charset.defaultCharset());
for(String line : lines) {
// String[] userParams = line.split(";");
//String name = userParams[0];
//String number= userParams[1];
//String mail = userParams[2];
sb.append(line);
}
String jdbcString = sb.toString();
System.out.println("JDBC statements read from file: " + jdbcString );
} catch (IOException e) {
e.printStackTrace();
}
}
or maybe this:
String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);
Just do that:
final FileChannel fc;
final String theFullStuff;
try (
fc = FileChannel.open(path, StandardOpenOptions.READ);
) {
final ByteBuffer buf = ByteBuffer.allocate(fc.size());
fc.read(buf);
theFullStuff = new String(buf.array(), theCharset);
}
nio for the win! :p
You could always create a Buffered reader e.g.
File anInputFile = new File(/*input path*/);
FileReader aFileReader = new FileReader(anInputFile);
BufferedReader reader = new BufferedReader(aFileReader)
String yourSingleString = "";
String aLine = reader.readLine();
while(aLine != null)
{
singleString += aLine + " ";
aLine = reader.readLine();
}
Lets say I have a text file called: data.txt (contains 2000 lines)
How do I read given specific line from: 500-1500 and then 1500-2000
and display the output of specific line?
this code will read whole files (2000 line)
public static String getContents(File aFile) {
StringBuffer contents = new StringBuffer();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null;
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
How do I modify above code to read specific line?
I suggest java.io.LineNumberReader. It extends BufferedReader and
you can use its LineNumberReader.getLineNumber(); to get the current line number
You can also use Java 7 java.nio.file.Files.readAllLines which returns a List<String> if it suits you better
Note:
1) favour StringBuilder over StringBuffer, StringBuffer is just a legacy class
2) contents.append(System.getProperty("line.separator")) does not look nice
use contents.append(File.separator) instead
3) Catching exception seems irrelevant, I would also suggest to change your code as
public static String getContents(File aFile) throws IOException {
BufferedReader rdr = new BufferedReader(new FileReader("aFile"));
try {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
} finally {
rdr.close();
}
}
now code looks cleaner in my view. And if you are in Java 7 use try-with-resources
try (BufferedReader rdr = new BufferedReader(new FileReader("aFile"))) {
StringBuilder sb = new StringBuilder();
// read your lines
return sb.toString();
}
so finally your code could look like
public static String[] getContents(File aFile) throws IOException {
try (LineNumberReader rdr = new LineNumberReader(new FileReader(aFile))) {
StringBuilder sb1 = new StringBuilder();
StringBuilder sb2 = new StringBuilder();
for (String line = null; (line = rdr.readLine()) != null;) {
if (rdr.getLineNumber() >= 1500) {
sb2.append(line).append(File.pathSeparatorChar);
} else if (rdr.getLineNumber() > 500) {
sb1.append(line).append(File.pathSeparatorChar);
}
}
return new String[] { sb1.toString(), sb2.toString() };
}
}
Note that it returns 2 strings 500-1499 and 1500-2000
A slightly more cleaner solution would be to use FileUtils in apache commons.
http://commons.apache.org/io/api-release/org/apache/commons/io/FileUtils.html
Example snippet:
String line = FileUtils.readLines(aFile).get(lineNumber);
The better way is to use BufferedReader. If you want to read line 32 for example:
for(int x = 0; x < 32; x++){
buf.readLine();
}
lineThreeTwo = buf.readLine();
Now in String lineThreeTwo you have stored line 32.
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.