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.
Related
I have two different ways to read the file but I am not sure how to proceed to converting the text to a string and then an if then statement like...
if string contains ":"
true string = "string"
false string = ,,"string"
package test;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class ReadStringFromFileLineByLine {
public static void main(String[] args) {
try {
File file = new File("foo.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
String trim;
while ((line = bufferedReader.readLine()) != null) {
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println("Contents of file:");
System.out.println(stringBuffer.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
}
But I don't believe I am using the trim command appropriately
Your question doesn't really communicate clearly the intent of the program. What exactly are you trying to do? If your file is text-based, there is no "conversion to String" needed. Also "save the file as an output" isn't clear either. Do you want to save a new file, overwrite the existing file, or append the existing file. All of these scenarios are handled differently. Taking this by parts:
First point: Your Scantest class works. Given a file foo.txt in the project folder, the class will print out the contents of the file.
Second point: Your class ReadStringFromFileLineByLine works with my own foo.txt just like the first class. So, there might be something wrong with your test.txt file. This is probably the most important thing when testing (making all conditions equal). If the conditions for testing are not equal, the tests will most likely be inconclusive (which is why I suspect happened in your case).
Third point: None of your classes attempted to make any modifications to the obtained strings or made modifications to the file. If you were to write to a file, you have to consider the following: Append vs. Overwrite. All it takes is the use of a simple boolean value:
FileWriter fw = new FileWriter(file.getAbsoluteFile()); // overwrites contents of file
FileWriter fw = new FileWriter(file.getAbsoluteFile(), true); // appends to file
The FileWriter single argument contructor calls the two-argument constructor passing false to it. Therefore, the FileWriter overwrites instead of appends. This is important because if you handle the file line by line, it is possible that at the end, your file will contain only the last line you "modified." If you choose to append, the new String will be added to the end of the line. So this is not good either. If you want to process a file line by line, made modifications to any given line, AND save the line to the same file, your best option is to use RandomAccessFile. This class allows you to write 'X' number of characters starting on a given offset. In this case, this "offset" is the "address" of the current line; putting it simply: the offset is equal to the number of characters already processed. So, for the first line, the offset is 0, for line 2 is the number of characters in line 1, and so forth.
I can add this as an update if you need it, but I did not see anything in your code that attempted to change the file in any way. I was just going by your title.
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.
Im still teaching myself Java so I wanted to try to read a text file and step 1) output it to console and step 2) write the contents to a new txt file.
Here is some code I have google'd to start with and it is reading the file, but when I output the line contents to the console I get the following (looks like its outputting in unicode or something... like every character as an extra byte associated to it....
ÿþFF□u□l□l□ □T□i□l□t□ □P□o□k□e□r□ <SNIP>
Here is what the first line of the file looks like when I open in via notepad:
Full Tilt Poker Game #xxxxxxxxxx: $1 + $0.20 Sit & Go (xxxxxxxx), Table 1 - 15/30 - No Limit Hold'em - 22:09:45 ET - 2009/12/26
Here is my code, do I need to specify the encoding to display txt file contents to the console? I assumed that simple text would be straight forward for java...but Im new and don't understand much about how finicky java is yet.
EDIT: I dont know if it matters but Im using Eclipse as my IDE currently.
package readWrite;
import java.io.*;
public class Read {
public static void main(String args[])
{
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader("C:\\Users\\brian\\workspace\\downloads\\poker_text.txt"));
String line = reader.readLine();
while (line!=null) {
// Print read line
System.out.println(line);
// Read next line for while condition
line = reader.readLine();
}
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
} finally {
try { if (reader!=null) reader.close(); } catch (Exception e) {}
}
}
}
The ÿþ at the beginning appears to be a Byte Order Mark for a UTF-16 encoded file.
http://en.wikipedia.org/wiki/Byte_order_mark#UTF-16
You might need to read the file in a different manner so Java can convert those UTF-16 characters to something your System.out can display.
Try something like this
FileInputStream fis = new FileInputStream("filename");
BufferedReader reader = new BufferedReader(new InputStreamReader(fis, "UTF-16"));
OR
Open up your text file in notepad again, and File/Save As. On the save screen (at least in windows 7) there is a pulldown with the encoding setting. Choose ANSI or UTF-8
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).
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();
}
}
}