How to add newlines while writing to file using java? - java

String filepath=jTextField1.getText();
FileReader fr;
try {
fr = new FileReader("C:\something.txt");
BufferedReader br = new BufferedReader(fr);
String sf="";
while((br.readLine())!=null){
sf=sf+br.readLine()+"\n";
}
jTextArea1.setText(sf);
} catch (Exception ex) {
Logger.getLogger(DesktopApplication1View.class.getName()).log(Level.SEVERE, null, ex);
}
The output file contain read character write in single line the whole length. How to get file with newlines?

According to your code you are READING a file and then outputting the text to what looks like a swing text component. I don't see where it is being declared so I can't say for sure what kind of component it is. You need to set your Text component to be multiline.

Instead of the "\n", use System.getProperty("line.separator") to ensure that you use the right line separator for your operating system.
As Manoj suggested, use StringBuilder instead of concatenating a String.
And, as maple_shaft already suggested, you need to set your Swing Text component to accept a multi-line string.

Related

Writing a javafx textarea to a textfile with linebreaks

So i'm currently trying to save the contents of a javafx textarea to a text file using the formatter class. The problem is that the text just gets saved in one line, without any line breaks.
This is the code i'm using for the Writing to the textFile
File file = new File(link);
Formatter formatter = null;
try {
formatter = new Formatter(file);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
formatter.format(textArea.getText() + "\n");
EDIT:
I found the problem: It is the fault of Windows Notepad. When i open the txt file in a other texteditor like notepadd++, it works just fine
do you really need to use the Formatter class? I suppose this class produces line separators (only) for the %n placeholder (but appears to be ignoring newline characters) in the contents of the format parameter (see also the corresponding javadoc):
format(String format, Object... args)
// Writes a formatted string to this object's destination using the specified format string and arguments.
One solution might be to specify the format string as "%s%n" (indicating that you want to format a String, followed by a line break) and pass the TextArea's contents, e.g. formatter.format("%s%n", textArea.getText()), if you really need to use the formatter.
Otherwise, you may just as well directly output the contents of the textArea to the file via some Writer:
FileWriter w = new FileWriter(file);
w.write(textArea.getText());
w.close();
you have to close the formatter
formatter.close();
The Formatter output is buffered in memory first. SO you have to close your formatter once you are done.
use finally block for this
try {
//code
} catch{
//code
}
finally {
formatter.close();
}
In my project I write the contents of a TextArea as follows:
byte[] contents = area.getText().getBytes(StandardCharsets.UTF_8);
Files.createDirectories(path.getParent());
Files.write(path, contents, StandardOpenOption.CREATE);
Which saves the contents as a UTF-8 encoded text file. This includes \n. Given that I'm working on Linux, I did not check if it actually is \n\r or not, my guts tell me it is only \n.

Java: How to scan from a user specified file

More specifically, how could I write code that could create a scanner for any text file that the user enters? For instance, one user might want to scan text from "foo.txt," and another might want to read from "bar.txt." How do I compensate for this?
You can simply make a function that opens a file and returns the reader so that you can read each line:
public BufferedReader readFromFile(String path) {
try {
return new BufferedReader(new FileReader(path));
} catch (IOException e) {
e.printStackTrace();
}
}
Then use the BufferedReader which it returns and iterate through each line! Hope it helps!
You can take the path to the file as an input to the program. For taking input, you can have a look at http://www.programmingsimplified.com/java/source-code/java-program-take-input-from-user
Once you have this path in a variable, you can replace the hardcoded file names by this variable instead.

Replace All Backslashes on a Property File

I was looking at a Properties file I'm testing and I realized that every time I do a Properties.store() values that contain characters like : and / receive a backslash, but I want my property file to be read by other programs that are not written in Java (so they will not use the Properties library) and those backslashes are causing problems on them. Is there any way to save the file without those?
I've tried building this function, which is called after the Properties file has been saved:
private void replaceInFile(File file) throws IOException {
File tmpFile = new File("/sdcard/test.prop");
FileWriter fw = new FileWriter(tmpFile);
Reader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
while (br.ready()) {
fw.write(br.readLine().replaceAll("\\", "") + "\n");
}
fw.close();
br.close();
fr.close();
}
But I'm getting this error when the function is called:
02-03 13:05:34.757: E/AndroidRuntime(15558): java.util.regex.PatternSyntaxException: Syntax error U_REGEX_BAD_ESCAPE_SEQUENCE near index 1:
\
^
These are special characters. They must be escaped with a slash.
= and : are symbols that separate key from value. What if you have foo=bar=baz? Or foo:bar:baz? Which is the key and which is the value
If you want to enforce different rules, then implement your own mechanism and don't use java.util.Properties. For the complete set of rules see Properties.load(..)
You can, after storing the properties, 1. read to string 2. replace escaped characters. 3. write the new string to file.

How to replace multiple occurences of a string in a text file with a variable entered by the user and save all to a new file?

public static void main(String args[])
{
try
{
File file = new File("input.txt");
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "000000", oldtext = "414141";
while((line = reader.readLine()) != null)
{
oldtext += line + "\r\n";
}
reader.close();
// replace a word in a file
//String newtext = oldtext.replaceAll("drink", "Love");
//To replace a line in a file
String newtext = oldtext.replaceAll("This is test string 20000", "blah blah blah");
FileWriter writer = new FileWriter("input.txt");
writer.write(newtext);writer.close();
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
A couple suggestions on your sample code:
Have the user pass in old and new on the command line (i.e., args[0] and args1).
If it's sufficient to do this a line at a time, it's going to be much more efficient to read a line, replace old -> new, then stream it out.
Also check out StringUtils and IOUtils, which may make your life easier in this case.
Easiest is the String.replace(oldstring, newstring), or String.replaceAll(regex, newString) function, you can just read the one file and write the replacement into a new file (or do it line by line if you're concerned about file size).
After reading your last comment - that's a totally different story... the preferred solution would be to parse the css file into an object model (like DOM), apply the changes there and serialize the model to css afterwards. It's much easier to find all color attributes in DOM and change them compared to doing the same with search and replace.
I've found some CSS parser in the wild wild web, but none of them looked like being capable of writing CSS files.
If you wanted to replace the color names with search and replace, you'd search for 'color:<colorname>' and replace it with 'color:<youHexColorValue>'. You may have to do the same for 'color:"<colorname>"', because the color name can be set in double quotes (another argument for using a CSS parser..)
String.replaceAll() is the easiest way to do it. Just read the complete CSS file into one String, replace all as suggested above and write the new String to the same (or a temporary) file (first).

How to delete a data from a file through java?

I want to read a file in java. And then, I want to delete a line from that file without the file being re-written.
How can I do this?
Someone suggested me to read/write to a file without the file being re-written with the help of RandomAccessFile. How to write data to a file through java?
Specifically, that files contains lines. One line contains three field - id, name and profession - separated by \t. I want to read that file through a Reader or InputStream or any other way and then search for a line that has the specified keyword (say 121) and then wants to delete that whole line.
This operation needs to be performed without the whole file being re-written
I don't think you can alter a file on a filesystem in any way without writing to it, including deleting a line.
Do you mean you want to write the file without altering the file's metadata, like the last modified time?
Based on your updated question:
I don't think you can do what you're asking to do here. You can't remove bytes from a file once the file has been written, note no deleteByte or removeByte methods in RandomAccessFile.
I suggest moving the content of your file to a database - that allows this kind of record-oriented operation.
The alternative is, you have to rewrite the file. Sorry!
"Lines" are an abstract concept -- they're just an arbitrary sequence of bytes terminated by "\n". BufferedWriters and their ilk don't support textual editing in this way, so you'll have to rewrite the file in its entirety.
In general, what you want to do is:
open a reader
read content into some suitable data structure
close the reader
change data/records which need to be changed in this data structure
open a FileWriter with append == false
write content of data structure to resulting file
close FileWriter
add a marker in your lines saying if your line is deleted or not : this will make a software delete instead od a hardware delete.
if you have to insert new lines, you then can reuse those that are marked as deleted.
The below code searchs the line or fields in a single text file reads the file line by line
then the line or fields can be replaced by " " or any other string. Here we use the pattern and Matcher classes.
If this not clearing your question do let me know.
import java.io.;
import java.util.regex.;
import java.util.Properties;
public class DeleteLine
{
public static void main(String[] args)
{
BufferedReader br = null;
try
{
String line=null;
File f = new File("d:/xyz.txt");
String replaceString=properties.getProperty("replaceAll.String");
;
br = new BufferedReader(new FileReader("d:/giri/scjp/");
while ( (line = br.readLine()) != null )//BufferedReader contains readline method
{
Pattern p=Pattern.compile(searchString);/*here u an specify the line u want to delete */
Matcher m=p.matcher(line);
line=m.replaceAll(replaceString);/*here replace String u can " " so that it will be emptied */
System.out.println(line);
}
//System.out.println(line);
}
}
}
br = new BufferedReader(new FileReader("d:/xyz.txt"));
String line = null;
}
catch (FileNotFoundException e)
{
System.out.println("File couldnt find");
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}

Categories

Resources