How to get a text file read line by line? - eclipse

I am creating an application which is text file reader but It reads the text file content line by line and then if a reserved word is red a function will execute.
For example I have a text file that contains the reserve word [PlaySound]+ sound file on its first line, when the reader reads the line a function will execute and plays the music file that is with the reserve word.
So is it possible to create this? and if it is how can i make the line reader?

File file = new File("inputFile.txt");
Scanner sc = null;
try {
sc = new Scanner(file);
String line = null;
while (sc.hasNextLine()) {
String soundFile = null;
line = sc.nextLine();
if (line.indexOf("[PlaySound]") >= 0) {
soundFile = // some regex to extract the sound file from the line
playSoundFile(soundFile);
}
}
sc.close();
}
catch (FileNotFoundException e) {
e.printStackTrace();
}
finally {
if (sc != null) { sc.close(); }
}

Related

MalformedInputException: Input length = 1 while reading text file with Files.readAllLines(Path.get("file").get(0);

Why am I getting this error? I'm trying to extract information from a bank statement PDF and tally different bills for the month. I write the data from a PDF to a text file so I can get specific data from the file (e.g. ASPEN HOME IMPRO, then iterate down to what the dollar amount is, then read that text line to a string)
When the Files.readAllLines(Path.get("bankData").get(0) code is run, I get the error. Any thoughts why? Encoding issue?
Here is the code:
public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\wmsai\\Desktop\\BankStatement.pdf");
PDFTextStripper stripper = new PDFTextStripper();
BufferedWriter bw = new BufferedWriter(new FileWriter("bankData"));
BufferedReader br = new BufferedReader(new FileReader("bankData"));
String pdfText = stripper.getText(Loader.loadPDF(file)).toUpperCase();
bw.write(pdfText);
bw.flush();
bw.close();
LineNumberReader lineNum = new LineNumberReader(new FileReader("bankData"));
String aspenHomeImpro = "PAYMENT: ACH: ASPEN HOME IMPRO";
String line;
while ((line = lineNum.readLine()) != null) {
if (line.contains(aspenHomeImpro)) {
int lineNumber = lineNum.getLineNumber();
int newLineNumber = lineNumber + 4;
String aspenData = Files.readAllLines(Paths.get("bankData")).get(0); //This is the code with the error
System.out.println(newLineNumber);
break;
} else if (!line.contains(aspenHomeImpro)) {
continue;
}
}
}
So I figured it out. I had to check the properties of the text file in question (I'm using Eclipse) to figure out what the actual encoding of the text file was.
Then, when creating the file in the program, encode the text file to UTF-8 so that Files.readAllLines could read and grab the data I wanted to get.

Why won't BufferedWriter write URL content to text file?

I'm trying to write the text from the URL to a text file in batches of 35 lines, pushing enter to continue to the next batch of 35 lines. If I don't try and write to the file in batches of 35 lines it works great and writes all of the content to the text file. But when I try and use the if statement to print in batches of 35 it won't print to the file unless I push enter around 15 times. And even then it doesn't print everything. I seems like it has something to do with the if statement but I can't figure it out.
String urlString = "https://www.gutenberg.org/files/46768/46768-0.txt";
try {
URL url = new URL(urlString);
try(Scanner input = new Scanner(System.in);
InputStream stream = url.openStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\Users\\mattj\\Documents\\JuliusCeasar.txt"));) {
String line;
int PAGE_LENGTH = 35;
int lineCount = 0;
while ((line = reader.readLine()) != null) {
System.out.println(line);
writer.write(line + "\n");
lineCount++;
if (lineCount == PAGE_LENGTH){
System.out.println();
System.out.println("- - - Press enter to continue - - -");
input.nextLine();
lineCount = 0;
}
}
}
} catch (MalformedURLException e) {
System.out.println("We encountered a problem regarding the following URL:\n"
+ urlString + "\nEither no legal protocol could be found or the "
+ "string could not be parsed.");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Attempting to open a stream from the following URL:\n"
+ urlString + "\ncaused a problem.");
e.printStackTrace();
}
I don't know Java, but there's very similar concepts in .NET. I think there's a couple of things to consider here.
BufferWriter will not write to the file immediately, it acts - as the name suggests - as a buffer, collecting up write requests over time then doing it in batch. BufferWriter has a flush method to flush the 'queued' up writes to the file immediately - so I'd do this when you hit your 35 (never flush on every write).
Also, BufferedReader and BufferedWriter are closable, so ensure to wrap them in a try statement to make sure resources are properly unlocked/cleared.

Saving jTextPane text not working properly

I'm trying to save a "history" I'm building after you sent a command from a line, so every time you press Enter the commands goes to the jTextPane with a line separator... However when I save the file it doesn't seem to get the line separator. Example, my jTextPane has something like:
Create database user
use database user
show tables from database
Instead of saving the workspace just like that, it gives me this:
Create database useruse database usershow tables from database
What should I do? Here's my code
String ar;
String TEXTO = jTextPane1.getText() + System.lineSeparator();
FileFilter ft = new FileNameExtensionFilter("Text Files", ".txt");
FC.setFileFilter(ft);
int returnVal = FC.showSaveDialog(this);
if (returnVal == javax.swing.JFileChooser.APPROVE_OPTION) {
java.io.File saved_file = FC.getSelectedFile();
String file_name = saved_file.toString();
File archivo;
ar = "" + file_name + ".txt";
archivo = new File(ar);
try {
if (saved_file != null) {
try (FileWriter GUARDADO = new FileWriter(ar)) {
GUARDADO.write(TEXTO);
}
}
} catch (IOException exp) {
System.out.println(exp);
}
}
You need to use :
jTextPane1.getDocument().getText(0,jTextPane1.getDocument().getLength());
The issue is that you need to use /n instead of System.lineSeparator. The JTextPane behavior doesn't depends on the System.

How to update a text file which always contains a single line?

I have the following code to read a line from a text file.
In the UpdateFile() method I need to delete the existing one line and update it with a new line.
Can anybody please provide any ideas?
Thank you.
FileInfo JFile = new FileInfo(#"C:\test.txt");
using (FileStream JStream = JFile.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
{
int n = GetNUmber(JStream);
n = n + 1;
UpdateFile(JStream);
}
private int GetNUmber(FileStream jstream)
{
StreamReader sr = new StreamReader(jstream);
string line = sr.ReadToEnd().Trim();
int result;
if (string.IsNullOrEmpty(line))
{
return 0;
}
else
{
int.TryParse(line, out result);
return result;
}
}
private int UpdateFile(FileStream jstream)
{
jstream.Seek(0, SeekOrigin.Begin);
StreamWriter writer = new StreamWriter(jstream);
writer.WriteLine(n);
}
I think the below code can do your job
StreamWriter writer = new StreamWriter("file path", false); //false means do not append
writer.Write("your new line");
writer.Close();
If you're just writing a single line, there's no need for streams or buffers or any of that. Just write it directly.
using System.IO;
File.WriteAllText(#"C:\test.txt", "hello world");
var line = File.ReadLines(#"c:\temp\hello.txt").ToList()[0];
var number = Convert.ToInt32(line);
number++;
File.WriteAllText(#"c:\temp\hello.txt", number.ToString());
Manage the possible exceptions, file exists, file has lines, the cast......

Eclipe PDE: Jump to line X and highlight it

A qustion about Eclipse PDE development: I write a small plugin for Eclipse and have the following
* an org.eclipse.ui.texteditor.ITextEditor
* a line number
How can I automatically jump to that line and mark it? It's a pity that the API seems only to support offsets (see: ITextEditor.selectAndReveal()) within the document but no line numbers.
The best would be - although this doesn't work:
ITextEditor editor = (ITextEditor)IDE.openEditor(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(), file, true );
editor.goto(line);
editor.markLine(line);
It this possible in some way? I did not find a solution
on the class DetailsView I found the following method.
private static void goToLine(IEditorPart editorPart, int lineNumber) {
if (!(editorPart instanceof ITextEditor) || lineNumber <= 0) {
return;
}
ITextEditor editor = (ITextEditor) editorPart;
IDocument document = editor.getDocumentProvider().getDocument(
editor.getEditorInput());
if (document != null) {
IRegion lineInfo = null;
try {
// line count internaly starts with 0, and not with 1 like in
// GUI
lineInfo = document.getLineInformation(lineNumber - 1);
} catch (BadLocationException e) {
// ignored because line number may not really exist in document,
// we guess this...
}
if (lineInfo != null) {
editor.selectAndReveal(lineInfo.getOffset(), lineInfo.getLength());
}
}
}
Even though org.eclipse.ui.texteditor.ITextEditor deals wiith offset, it should be able to take your line number with the selectAndReveal() method.
See this thread and this thread.
Try something along the line of:
((ITextEditor)org.eclipse.jdt.ui.JavaUI.openInEditor(compilationUnit)).selectAndReveal(int, int);