Move first line of .txt file add to last line - java

I have a.txt list trying to move the first line to the last line in Java
I've found scripts to do the following
Find "text" from input file and output to a temp file. (I could set
"text" to a string buffRead.readLine ??) and then...
delete the orig file and rename the new file to the orig?
Please for give me I am new to Java but I have done a lot of research and can't find a solution for what I thought would be a simple script.

Because this is Java and concerns file IO, this is a non-trivial setup. The algorithm itself is simple, but the symbols required to do so are not immediately evident.
BufferedReader reader = new BufferedReader(new FileReader("fileName"));
This gives you an easy way to read the contents of the file fileName.
PrintWriter writer = new PrintWriter(new FileWriter("fileName"));
This gives you a simple way to write to the file. The API to do so is the exact same as System.out when you use a PrintWriter, thus my choice to use one here.
At this point its a simple matter of reading the file and echoing it back in the correct order.
String text = reader.readLine();
This saves the first line of the file to text.
while (reader.ready()) {
writer.println(reader.readLine());
}
While reader has text remaining in it, print the lines into the writer.
writer.println(text);
Print the line that you saved at the start.
Note that if your program does anything else (and it's just a good habit anyway), you want to close your IO streams to avoid leaking resources.
reader.close();
writer.close();
Alternatively, you could also wrap the entire thing in a try-with-resources to perform the same cleanup automatically.

Scanner fileScanner = new Scanner(myFile);
fileScanner.nextLine();
This will return the first line of text from the file and discard it because you don't store it anywhere.
To overwrite your existing file:
FileWriter fileStream = new FileWriter("my/path/for/file.txt");
BufferedWriter out = new BufferedWriter(fileStream);
while(fileScanner.hasNextLine()) {
String next = fileScanner.nextLine();
if(next.equals("\n") out.newLine();
else out.write(next);
out.newLine();
}
out.close();
Note that you will have to be catching and handling some IOExceptions this way. Also, the if()... else()... statement is necessary in the while() loop to keep any line breaks present in your text file.
Add the same line to the last line of this file have a look into this link https://stackoverflow.com/a/37674446/6160431

Related

PrintWriter not outputing to file

Whenever the next segment of code is run, I get the new csv file created, but I don't get anything written to it:
PrintWriter fout = null;
try {
// create file
fout= new PrintWriter("EEGLogger.csv");
String headerFile = "IED_COUNTER, IED_INTERPOLATED, IED_RAW_CQ, IED_AF3, IED_F7, IED_F3, IED_FC5, IED_T7, " +
"IED_P7, IED_O1, IED_O2, IED_P8, IED_T8, IED_FC6, IED_F4, IED_F8, IED_AF4, " +
"IED_GYROX, IED_GYROY,IED_TIMESTAMP";
// Writes the header to the file
fout.println(headerFile);
fout.println();
...
I do a fout.close() in a finally statement, but that still doesn't help get any output to the file. Any ideas here?
Either:
You are looking in the wrong place, i.e. not the current working directory, or
You don't have write access to the current working directory.
If you had used a FileWriter and not got an IOException, that would rule out (2).
I've seen about a million answers and comments here this week claiming that the current working directory equals the location of the JAR file, but it doesn't.
You could open a FileWriter
fout = new PrintWriter(new FileWriter("EEGLogger.csv"));
...
fout.flush();
fout.close()
I believe the PrintWriter is intended for formatting and character encoding. api docs states Prints formatted representations of objects to a text-output stream and as well Methods in this class never throw I/O exceptions.
Using the FileWriter as parameter would force you to handle any IOException that may happen so if the file is not created or not writable, you will immediately get this information.
Another situation can happen if the file is created and you are just looking for the file at incorrect location. I'd suggest to create a File object too, to see where the file really resides (what's your real working directory)
File f = new File("EEGLogger.csv");
fout = new PrintWriter(new FileWriter(f));
System.out.println(f.getAbsolutePath());

is there way access specific line in file (without looping) java - libgdx

Hi i am using LibGDX to program android.
Is there some way to sraightforward access specific line on the file without going through all the lines and reading them until i reach desired line? (Can I just say I want to read line number so-and-so?)
I know there are such methods:
FileHandle file = Gdx.files.internal("list.txt");
BufferedReader reader = new BufferedReader(file.reader());
reader.readLine(); <--- but it reads only first line !
//// or using scanner
scanner1 = new Scanner(new File("list.txt"));
scanner1.nextLine(); <--- also reads first line ..
Can I do it without looping through unnecessary lines? Any solutions, workarounds welcome. Thanx

Clear contents of a file in Java using RandomAccessFile

I am trying to clear the contents of a file I made in java. The file is created by a PrintWriter call. I read here that one can use RandomAccessFile to do so, and read somewhere else that this is in fact better to use than calling a new PrintWriter and immediately closing it to overwrite the file with a blank one.
However, using the RandomAccessFile is not working, and I don't understand why. Here is the basic outline of my code.
PrintWriter writer = new PrintWriter("temp","UTF-8");
while (condition) {
writer.println("Example text");
if (clearCondition) {
new RandomAccessFile("temp","rw").setLength(0);
// Although the solution in the link above did not include ',"rw"'
// My compiler would not accept without a second parameter
writer.println("Text to be written onto the first line of temp file");
}
}
writer.close();
Running the equivalent of the above code is giving my temp file the contents:(Lets imagine that the program looped twice before clearCondition was met)
Example Text
Example Text
Text to be written onto the first line of temp file
NOTE: writer needs to be able to write "Example Text" to the file again after the file is cleared. The clearCondition does not mean that the while loop gets broken.
You want to either flush the PrintWriter to make sure the changes in its buffer are written out first, before you set the RandomAccessFile's length to 0, or close it and re-open a new PrintWriter to write the last line (Text to be written...). Preferably the former:
if (clearCondition) {
writer.flush();
new RandomAccessFile("temp","rw").setLength(0);
You'll be lucky if opening the file twice at the same time works. It isn't specified to work by Java.
What you should do is close the PrintWriter and open a new one without the 'append' parameter, or with 'append' set to 'false'.

Optimized solution for reading from a file, manipulating its data and writing to another file in JAVA

I have a file "File 1" containing approximately 0.1 million lines.
I have to read this file line by line and add some text to each line and write it to another file "File 2".
I don't want to perform write operation on "File 2" for each line as its expensive.
Which is the better option to save each modified line of "File 1" in memory?
ArrayList or StringBuilder or anything else?
And at the end I will write the complete data in memory to "File 2".
Using an appropriately sized buffer might not be as expensive as you might think. Keeping all of the content in memory when your problem looks to be more of a stream processing one sounds like a bad idea.
Reading File 1 from a BufferedReader, changing something and passing the result to a BufferedWriter might be your best bet.
Just use BufferedOutputStream to reduce number of physical writes:
BufferedReader reader = new BufferedReader(
new InputStreamReader (new FileInputStream ("input.txt")));
Writer writer =
new OutputStreamWriter(
new BufferedOutputStream (new FileOutputStream ("output.txt")));
String line;
while ((line = reader.readLine ()) != null)
{
writer.write (line + " foo \n");
}
reader.close ();
writer.close ();
Well i dont think reading it line by line will huge performance impact , if you are using java 5 and above you can make use of java.nio to make use of native OS processes
Check this link for more info
http://docs.oracle.com/javase/tutorial/essential/io/file.html

java output html code to file

I have a chunk of html code that should be outputted as a .html file, in java. The pre-written html code is the header and table for a page, and i need to generate some data, and output it to the same .html file. Is there an easier way to print the html code than to do prinln() line by line? Thanks
You can look at some Java libraries for parsing HTML code. A quick Google search tuns up a few. Read in the HTML and then use their queries to manipulate the DOM as needed and then spit it back out.
e.g. http://jsoup.org/
Try using a templating engine, MVEL2 or FreeMarker, for example. Both can be used by standalone applications outside of a web framework. You lose time upfront but it will save you time in the long run.
JSP (Java Server Pages) allows you to write HTML files which have some Java code easily embedded within them. For example
<html><head><title>Hi!</title></head><body>
<% some java code here that outputs some stuff %>
</body></html>
Though that requires that you have an enterprise Java server installed. But if this is on a web server, that might not be unreasonable to have.
If you want to do it in normal Java, that depends. I don't fully understand which part you meant you will be outputting line by line. Did you mean you are going to do something like
System.out.println("<html>");
System.out.println("<head><title>Hi!</title></head>");
System.out.println("<body>");
// etc
Like that? If that's what you meant, then don't do that. You can just read in the data from the template file and output all the data at once. You could read it into a multiline text string of you could read the data in from the template and output it directly to the new file. Something like
while( (strInput = templateFileReader.readLine()) != null)
newFileOutput.println(strInput);
Again, I'm not sure exactly what you mean by that part.
HTML is simply a way of marking up text, so to write a HTML file, you are simply writing the HTML as text to a file with the .html extension.
There's plenty of tutorials out there for reading and writing from files, as well as getting a list of files from a directory. (Google 'java read file', 'java write file', 'java list directory' - that is basically everything you need.) The important thing is the use of BufferedReader/BufferedWriter for pulling and pushing the text in to the files and realising that there is no particular code science involved in writing HTML to a file.
I'll reiterate; HTML is nothing more than <b>text with tags</b>.
Here's a really crude example that will output two files to a single file, wrapping them in an <html></html> tag.
BufferedReader getReaderForFile(filename) {
FileInputStream in = new FileInputStream(filename);
return new BufferedReader(new InputStreamReader(in));
}
public void main(String[] args) {
// Open a file
BufferedReader myheader = getReaderForFile("myheader.txt");
BufferedReader contents = getReaderForFile("contentfile.txt");
FileWriter fstream = new FileWriter("mypage.html");
BufferedWriter out = new BufferedWriter(fstream);
out.write("<html>");
out.newLine();
for (String line = myheader.readLine(); line!=null; line = myheader.readLine()) {
out.write(line);
out.newLine(); // readLine() strips 'carriage return' characters
}
for (String line = contents.readLine(); line!=null; line = contents.readLine()) {
out.write(line);
out.newLine(); // readLine() strips 'carriage return' characters
}
out.write("</html>");
}
To build a simple HTML text file, you don't have to read your input file line by line.
File theFile = new File("file.html");
byte[] content = new byte[(int) theFile.length()];
You can use "RandomAccessFile.readFully" to read files entirely as a byte array:
// Read file function:
RandomAccessFile file = null;
try {
file = new RandomAccessFile(theFile, "r");
file.readFully(content);
} finally {
if(file != null) {
file.close();
}
}
Make your modifications on the text content:
String text = new String(content);
text = text.replace("<!-- placeholder -->", "generated data");
content = text.getBytes();
Writing is also easy:
// Write file content:
RandomAccessFile file = null;
try {
file = new RandomAccessFile(theFile, "rw");
file.write(content);
} finally {
if(file != null) {
file.close();
}
}

Categories

Resources