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

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

Related

Move first line of .txt file add to last line

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

using Scanner to read a file

I found the following useful in the past for reading in text files:
new Scanner(file).useDelimiter("\\Z").next();
However I came across a file today that was only partially read in with this syntax. I'm not sure what makes this file special, it's just a .jsp
I found the below worked in this instance but I'd like to know why the previous method didn't work.
Scanner in = new Scanner(new FileReader(file));
String text = in.useDelimiter("\\Z").next();
Save the jsp file as .txt and try to read it using your first method. if it works i feel size can be the issue.

Best way in Java to write in the middle of a file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Best Way to Write Bytes in the Middle of a File in Java
I'm writing a program that modifies a PostScript file to add print properties, so I need to add lines in the middle of the file. These PostScript files are very large, and I want to know if the code I'm using is the most efficient. This code reads the source file and writes a temporary file adding a line where is needed.
Writer out = null;
Scanner scanner = null;
String newLine = System.getProperty("line.separator");
scanner = new Scanner(new FileInputStream(fileToRead));
out = new OutputStreamWriter(new FileOutputStream(fileToWrite));
String line;
while(scanner.hasNextLine()){
line = scanner.nextLine();
out.write(line);
out.write(newLine);
if(line.equals("%%BeginSetup")){
out.write("<< /Duplex true /Tumble true >> setpagedevice");
out.write(newLine);
}
}
scanner.close();
out.close();
Any help will be appreciated, thanks in advance.
Most of the old answers found on SO uses/links the old java.io.*
Oracle has nice examples how to do this using the "new" java 7 java.nio.* packages (usually with much better performance)
http://docs.oracle.com/javase/tutorial/essential/io/rafs.html
See RandomAccessFile and its example here: Fileseek - You can seek to a particular location in the file and write to it there.

Scanner No Line Found Exception

I am getting the following exception.
java.util.NoSuchElementException: No line found
I got this error while writing a larger program which needed to read from a text file, and so decided to do a test.
Scanner scan = new Scanner(new File("restrictions.txt");
String s1 = scan.nextLine();
System.out.println(s1);
And I still get the exception. I have a text file in the same folder as the class called restrictions.txt which has text in it. What am I doing wrong?
new File("restrictions.txt") will look for the file in the "Start dir" of your app - if you're using Eclipse, it's probably the root of your project.
To open the file next to your class, you can use the Scanner constructor which accepts an InputStream that you get by
YourClass.class.getResourceAsStream("restrictions.txt")
You should use if(in.hasNextLine()) before calling in.nextLine(). Otherwise for last line it will thrown Line not found exception.
Javadoc for Scanner
Do you need to specify a line ending so it knows what a line is?

Java Scanner unable to read file

I'm doing a very simple text-parsing program, using files given to me by a friend.
However, when I open the file using a Scanner like so,
Scanner scan = new Scanner(new File(path));
System.err.println(scan.hasNext());
while(scan.hasNextLine())
System.err.println(scan.nextLine());
System.err.println(scan.next());
result:
false
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:855)
at java.util.Scanner.next(Scanner.java:1364)
at Test.main(Test.java:18)
the scanner treats the file(which is some 1400 lines long) as empty.
Can anyone think of any reason a scanner might not be able to see a file? I suspect the fact that the file was imported from a Windows machine to a Linux machine may have something to do with it, but my mind is open to other possibilities
edited for formatting and code errors
I resolved it using new Scanner(new BufferedReader(new FileReader(fileName))) instead of new Scanner(new File(fileName))
Found the problem:
Looked at the file byte by byte. found an EOF character in the first byte.
Java was ignoring the rest of the file.
EDIT: Fisrt guess was wrong
The file might have 1400 lines full of whitespaces.
it maybe occurred for this problems:
1-your file maybe isn't created.
2-your file is in use for other programs.
3-the path address is false.

Categories

Resources