White Spaces Java Text File - java

Is is possible to remove the white spaces of a String in a text file in Java? I have tried my approach but doesn't working.
public static void main(String[] args) throws IOException {
File f = new File("ejer2.txt");
BufferedReader br = new BufferedReader(new FileReader(f));
String linea = br.readLine();
linea.replaceAll("\\s", "");
while (linea != null) {
System.out.println(linea);
linea = br.readLine();
}
br.close();
}
The only way I can get the white spaces out of the String is when I print the line out in the While loop by using the replaceAll method in the String class, but im trying to take them out of the Stringin the File, and I'm not sure if this is possible.

Try with this:
linea = linea.replaceAll("\\s+","")
EDIT: It is because you didn't save the value of your new string in your variable linea. You have to asign it.

If you want to actually replace the spaces in the file, you need to write to the file instead of just reading from it.
You'll need to add a linea.replaceAll line inside your while loop.
You'll need to store all these lines as well - I suggest using a Stringbuilder and adding everything you read to the builder (after you run replaceAll).
You'll also need to write the final text to the text file. I suggest using a PrintStream.
eg: PrintStream out = new PrintStream(new FileOutputStream("finalFile.txt"));
then out.print(yourStringBuilder.toString())

Related

How to load a text file to a string variable in java

I'm pretty new in the programming world, and i can't find a good explanation on how to to load a txt file to a string variable in java using eclpise.
So far, from what i have been able to understand, i am supposed to use the StdIn class, and i know that the txt file need to be located in my eclipse workspace (outside the source folder) but i don't know what excatly i need to write in the code to get the given file to load into the variable.
I could really use some help with this.
Although I'm not a Java expert, I'm pretty sure this is the information you're looking for It looks like this:
static String readFile(String path, Charset encoding)
throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return new String(encoded, encoding);
}
Basically all languages provide you with some methods to read from the file system you're in. Hope that does it for you!
Good luck with your project!
to read a file and store it in a String you can do it by using either String or StringBuilder:
you need to define BufferedReader to with constructor of FileReader to pass the name of the file and make it ready to read from file.
use StringBuilder to append every line of result to it.
when the reading finished add the result to String data.
public static void main(String[] args) {
String data = "";
try {
BufferedReader br = new BufferedReader(new FileReader("filename"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
sb.append(line);
sb.append("\n");
line = br.readLine();
}
data = sb.toString();
} catch (Exception e) {
e.printStackTrace();
}
}

Stop word removing went wrong

For some IR purpouses, I would like to extract some text snippet and before analyzing, I wish to remove stop words. To do so, I made a txt file of stop words and then using following code, trying to remove those useless words:
private static void stopWordRemowal() throws FileNotFoundException, IOException {
Set<String> stopWords = new LinkedHashSet<String>();
BufferedReader br = new BufferedReader(new FileReader("StopWord.txt"));
for(String line;(line = br.readLine()) != null;)
stopWords.add(line.trim());
BufferedReader br2 = new BufferedReader(new FileReader("text"));
FileOutputStream theNewWords=new FileOutputStream(temp);
for(String readReady;(readReady = br2.readLine()) != null;)
{
StringTokenizer tokenizer =new StringTokenizer(readReady) ;
String temp=tokenizer.nextToken();
if(!stopWords.equals(temp))
{
theNewWords.write(temp.getBytes());
theNewWords.write(System.getProperty("line.separator").getBytes());
}}
}
But in fact it does not working well. Considering the following example text snippet:
Text summarization is the process of extracting salient information from the source text and to present that
information to the user in the form of summary
the output will be like:
Text
summarization
is
the
process
of
extracting
salient
information
from
the
source
text
and
to
present
that
information
to
the
user
in
the
form
of
summary
it is almost like no effect. But I do not know why.
You should use contains method of Set and not equals method like:
if(!stopWords.contains(temp))//does set contains my string temp?
Instead of
if(!stopWords.equals(temp))//set equals to string? not possible

Removing commas from a text file

Im trying to remove all commas from my text file, where am i going wrong? I think its to do with the replaceAll field, ive done research into it, but cannot find any answers. I also need there to be a new line after a ";" as well as removing the commas. Thankyou in advance
`public static void open(){
// The name of the file to open.
String fileName = "Test.txt";
// 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) {
line.replaceAll(",","\\.");
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
}
}`
Strings are immutable in Java, so System.out.println(line.replaceAll(",","\\.")) is what you want. You want to print the returned value.
line.replaceAll(",","\\.");
Java Strings are immutable - this does not alter line but returns a new String with the desired replacement applied. Try assigning that to a variable instead:
String s = line.replaceAll(",","\\.");
or printing it directly:
System.out.println(line.replaceAll(",","\\."));
You may try like this:
String s = line.replaceAll(",","\\.");
Note Java strings are immutable
or you may choose to directly print it as:
System.out.println(line.replaceAll(",","\\."));
In you code when you say:
line.replaceAll(",","\\.");
then there is no change in the line and it returns a new String.
changing line.replaceAll(",","\\."); to line = line.replaceAll(",","\\."); should fix your problem.
As for putting newlines after ";" use line = line.replaceAll(";",";\n");
Try to load file with :
public static String readAllText(String filename) throws Exception {
StringBuilder sb = new StringBuilder();
Files.lines(Paths.get(filename)).forEach(sb::append);
return sb.toString();
}
then change what do you want.
String file = readAllText("myfile.txt");
file = file.replace(",","\\.);

Java create strings from Buffered Reader and compare Strings

I am using Java + Selenium 1 to test a web application.
I have to read through a text file line by line using befferedreader.readLine and compare the data that was found to another String.
Is there way to assign each line a unique string? I think it would be something like this:
FileInputStream fstream = new FileInputStream("C:\\write.txt");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
String[] strArray = null;
int p=0;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strArray[p] = strLine;
assertTrue(strArray[p].equals(someString));
p=p+1;
}
The problem with this is that you don't know how many lines there are, so you can't size your array correctly. Use a List<String> instead.
In order of decreasing importance,
You don't need to store the Strings in an array at all, as pointed out by Perception.
You don't know how many lines there are, so as pointed out by Qwerky, if you do need to store them you should use a resizeable collection like ArrayList.
DataInputStream is not needed: you can just wrap your FileInputStream directly in an InputStreamReader.
You may want to try something like:
public final static String someString = "someString";
public boolean isMyFileOk(String filename){
Scanner sc = new Scanner(filename);
boolean fileOk = true;
while(sc.hasNext() && fileOk){
String line = sc.nextLine();
fileOk = isMyLineOk(line);
}
sc.close();
return fileOk;
}
public boolean isMyLineOk(String line){
return line.equals(someString);
}
The Scanner class is usually a great class to read files :)
And as suggested, you may check one line at a time instead of loading them all in memory before processing them. This may not be an issue if your file is relatively small but you better keep your code scalable, especially for doing the exact same thing :)

How can I read text appended to the end of a file I already read?

I want to read a text file in Java. After I finish, some text will be appended by another application, and then I want to read that. Lets say there are ten lines. When the other app appends one more line, I dont want to read the whole file again; just the new line. How can I do this?
Something like this could work:
BufferedReader reader = .. // create a reader on the input file without locking it
while(otherAppWritesToFile) {
String line = reader.readLine();
while(line != null) {
processLine(line);
line = reader.readLine();
}
Thread.sleep(100);
}
Exception handling has been left out for the sake of simplicity.
Once you get an EOF indication, wait a little bit and then try reading again.
Edit: Here is teh codez to support this solution. You can try it and then change the control flow mechanisms as needed.
public static void main(final String[] args) throws IOException {
final Scanner keyboard = new Scanner(System.in);
final BufferedReader input = new BufferedReader(new FileReader("input.txt"));
boolean cont = true;
while (cont) {
String line = input.readLine();
while (line != null) {
System.out.println(line);
line = input.readLine();
}
System.out.println("EOF reached, add more input and type 'y' to continue.");
final String in = keyboard.nextLine();
cont = in.equalsIgnoreCase("y");
}
}
EDIT: Thanks for adding some code Tim. Personally, I would just do a sleep instead of waiting for user input. That would more closely match the users' requirements.
You could try using a RandomAccessFile.
Open the file and then invoke the length() to get the length of the file. Then you can use the readLine() method to get your data. Then the next time you open the file you can use the seek() method to position yourself to the previous end of the file. Then read the lines and save the new length of the file.

Categories