EDIT: I guess this thread can be closed, since all my questions have been answered! Thanks to everyone who helped me!
EDIT: I stumbled upon an error at openFileInput("myfilename.txt");. This is the error: The method openFileInput(String) is undefined for the type Game. I read an answer here: Android File I/O openFileInput() undefined, but must admit that I don't quite understand it...
I'm trying to read parts of a text file, till the token ";". This is the code I wrote:
InputStream instream = openFileInput("myfilename.txt");
String line=null;
InputStreamReader inputreader = new InputStreamReader(instream);
BufferedReader buffreader = new BufferedReader(inputreader);
while((line=buffreader.readLine())!=null){
String[] parts=line.split(";");
int intOne = Integer.parseInt(parts([0]);
int intTwo = Integer.parseInt(parts([1]);
String strLine = parts([3]);
}
public static void Start(){
while(there is text in the file){
// read first line till ';';
// name that variable intOne;
// read first line after ';' till next ';';
// name that variable intTwo;
// read next line, declare as strLine;
// System.out.println(strLine);
}
}
Beneath it is the idea of what it should do. But I have some questions:
Am I right to say that the String[] parts is an array?
I want to have a bigger file, but read only 3 lines per loop. Or could I, when I have a file of 100 lines, read that all at once, then recall them from the parts[]? Or would that take way too much time?
Where should the text file be? When I'm testing in Eclipse, in the project folder? And when I export it inside the jar?
Hope someone can answer my questions!
(My source is: Read specific string from each line of text file using BufferedReader in java, all credits to Gilbert Le Blanc!)
EDIT: When I do this in the file:
Hello,
I am coding;
Will the pars[0] be Hello,, because that's one line, or Hello, I am coding? And will it take the enter with it?
Another EDIT:
I wish to create some sort of textbased RPG engine, where you only have to edit the text file, to change the story. For example (in the text file):
30;60; //Score needed for this piece of the story
Hello!; // The text
Hi!;5; // The first possible answer; the score you'll get when you answer this
Shut up!;-5; // The second possible answer; the score you'll get when you answer this
What you rly want is reading one char after another. I used some nice BufferedSegmentReader from the framework Smooks, which could be interesting for you. Look at the sourcecode here:
http://grepcode.com/file/repo1.maven.org/maven2/org.milyn/milyn-smooks-all/1.5/org/milyn/edisax/BufferedSegmentReader.java
It reads characters one after another from a stream and puts it into a StringBuffer. There are delimiters to indicate when one "segment" is done reading, and after that you can work with this segment till you tell the BufferedSegmentReader to move on.
I think this rly suits your case and is an approach you are looking for.
Related
I know that similar questions have been asked before, but not exactly what I'm asking. To begin with, let me explain my purpose. I'm trying to write a kind of "remote shell" that will take in characters from the console (System.in) on character at a time and then send those to a remote session on another machine, write them to that machine and gather any characters it might output to return to my shell to display back to the user.
So, the issue is that System.in, no matter what I do, doesn't really support a "raw" mode where any type of reader is able to read just one character at a time UNTIL a terminator character is entered, typically new line.
Things I have tried, Using Scanner, using a buffered reader, creating a FileDescriptor.in and creating a fileInputStream from that, using a FileChannel and reading into a ByteBuffer that is one character long, etc. In all cases, it seems, System.in only makes characters available to the java application after a terminator character has been entered by the user. I'm convinced there is not a "java" way to do this, so the question is, does anyone have some native code, wrapped in a java library to do this? Its hard to find such a thing just searching GitHub.
BTW, for the remote console, I'm using the pty4J package. I've seen sample projects that connect to that code using other langauages, for example javaScript running in a browser to create a web based shell. Other languages all you to do a simple "get_char" on standard in.
Some examples of the code I've tried:
Scanner scanner = new Scanner(System.in);
FileDescriptor fd = FileDescriptor.in;
FileInputStream fis = new FileInputStream(fd);
FileChannel fc = fis.getChannel();
while(process.isAlive()) {
System.out.println(scanner.next());
// ByteBuffer bb = ByteBuffer.allocate(1);
// int c = fc.read(bb);
// int c = fis.read();
// System.err.println("Read " + c);
// if (c == 1) {
// os.write(bb.get());
// }
}
You can see that I've tried various methods to read the input: scanner.next(), fc.read(byteBuffer), fileInputStream.read(), etc. All attempts "wait" till a terminator character is entered.
Additionally, I have tried using the "useDelimiter" and "next(pattern)" methods on the scanner too. That's still not working.
Any pointer or help is much appreciated.
Below is an example of reading one character at a time until end of stream is reached. On linux, you type control-d to signal the end input. I think on Windows, you type control-c to end of input.
import java.io.*;
class Test {
public static void main(String[] args) throws IOException {
int c = 0;
while( (c=System.in.read()) != -1){
System.out.println((char) c);
}
}
}
I successfully read in data from csv files with this code
Scanner scanIt = new Scanner(new BufferedReader(new FileReader(filef)));
while (scanIt.hasNextLine())
{
String inputLine = scanIt.nextLine();
System.out.println(inputLine);
}
scanIt.close();
until I encountered this line (in the file) which seems to have a "carriage return" buried within the read line, located between- ,"TBD and TBD",
Incoming PR# & Doc#: ,"TBDTBD",,Funds Held By Sponsor/Unallocated
Funds,,,, $- ,,,NS02 , $- , $- ,
I am trying to solve this problem by tell the code to look for a carriage return "\n" preceded by a comma "," as a true end of line
while (scanIt.hasNext(","+"\n"))
but that did not solve the problem.
What are ideas to resolve this problem?
Thank you for taking the time to do this.
you need a CSV parser to properly read the file. The real solution is that a \n or \r in between " is not the end of a line.
Please use a proper CSV parser because this is not the only problem you will encounter. Data with a , could be another such problem. a CSV parser will solve all of these.
It is known that the dash (-) in a YAML file before the key value pair is necessary to show that it is separate block(it is what I think). Figure 1 shows the YAML I'm generating using YamlBeans jar.
field1:
- childfield1:
datafield1:
param1:
childparam: paramvalue
param2:
childparam2: paramvalue
param3:
childparam3: paramvalue
datafield2: value2
For my codebase can't be changed, I have to somehow create the YAMLs as shown in Figure 2 (a tab is appended in each line in yaml file) or remove the dash is removed. You can clearly observe that there are only two thin vertical lines in Figure 1 but three thin vertical lines in Figure 2 which shows the alignment of the blocks.
What I want to achieve is to remove that dash from the first block (at the child field) from the file. Using a YAML file reader and writer always introduces the dash.
Glancing quick at (but admittedly not being familiar with) YamlBeans, it doesn't look like it's easy to subclass the behavior of the Emitter. One option though is to generate a temporary form in memory, then manipulate the results when writing out to a file. For example
// let YamlWriter write its contents to an in-memory buffer
StringWriter temp = new StringWriter();
YamlWriter yamlOut = new YamlWriter(temp);
yamlOut.write(someObject);
// then dump the in-memory buffer out to a file, manipulating lines that
// start with a dash
PrintWriter out = new PrintWriter(new FileWriter(new File("someoutput.dat")));
LineNumberReader in = new LineNumberReader(new StringReader(temp.toString()));
String line;
while ((line = in.readLine()) != null) {
if (line.startsWith("-")) {
line = line.substring(1);
}
out.println(line);
}
my specifics may be off, but hopefully the approach of doing simple manipulations of a temporary copy is clear enough.
If I were personally doing this, I'd probably write a custom subclass of java.io.Writer and do the manipulation on the fly (but i haven't gone through YamlWriter/Emitter in enough detail to provide an example on how to do that)
I'm trying to print the text within the quotes in a file. May I have anyone to help me.
E.g : "Jayaramachandiran"
This line is in a text file,and I wanna read it and print it.
Why don't you check out this link:
How do I create a Java string from the contents of a file?
It seems someone has answered your question already. :)
The first answer to that question is your best bet.
P.S After reading the file into a string, just go ahead and output the string and voila!
You may use a BufferedReader to read.
See this example:
import java.io.*;
class YourClass {
public static void main (String[] args) throws IOException {
BufferedReader fr = new BufferedReader(new FileReader("yourfile.txt"));
String text = fr.readLine();
fr.close();
System.out.println(text);
}
}
You want to print a string from file, but removing characters, like the quotes, from it.
I think it's better first to read the string from file, then remove the quotes.
Check this page.
I'm trying to read a binary file but my program just stops at first line..
I think it's because of the strange characters the file has..I just want to extract some directions from it. Is there a way to do this?..
public static void main(String[] args) throws IOException
{
Scanner readF = new Scanner(new File("D:\\CurrentDatabase_372.txt"));
String line = null;
String newLine = System.getProperty("line.separator");
FileWriter writeF = new FileWriter("D:\\Songs.txt");
while (readF.hasNext())
{
line = readF.nextLine();
if (line.contains("D:\\") && line.contains(".mp3"))
{
writeF.write(line.substring(line.indexOf("D:\\"), line.indexOf(".mp3") + 4) + newLine);
}
}
readF.close();
writeF.close();
}
The file starts like this:
pppppamepD:\Music\Korn\Untouchables\03 Blame.mp3pmp3pmp3pKornpMetalpKornpUntouchablespKornpUntouchables*;*KornpKornpKornUntouchables003pMetalKornUntouchables003pBlameKornUntouchables003pKornKornUntouchables003pMP3pppppCpppÀppp#ppøp·pppŸú#pdppppppòrSpUpppppp€ppªp8›qpppppppppppp,’ppÒppp’ÍpET?ppppppôpp¼}`Ñ#ãâK†¡H¤*(DppppppppppppppppuÞѤéú:M®$#]jkÝW0ÛœFµú½XVNp`w—wâÊp:ºŽwâÊpppp8Npdpp¡pp{)pppppppppppppppppyY:¸[ªA¥Bi `Û¯pppppppppppp2pppppppppppppppppppppppppppppppppppp¿ÞpAppppppp€ppp€;€?€CpCpC€H€N€S€`€e€y€~p~p~€’€«€Ê€â€Hollow LifepD:\Musica\Korn\Untouchables\04 Hollow Life.mp3pmp3pmp3pKornpMetalpKornpUntouchablespKornpUntouchables*;*KornpKornpKornUntouchables004pMetalKornUntouchables004pHollow LifeKornUntouchables004pKornKornUntouchables004pMP3pppppCpppÀHppppppøp¸pppǺxp‰ppppppòrSpUpppppp€ppªp8›qpppppppppppp,’ppÒpppŠºppppppppppôpp¼}`Ñ#ãâK†¡H¤*(DpppppppppppppppppãG#™R‚CA—®þ^bN °mbŽ‚^¨pG¦sp;5p5ÓÐùšwâÊp
)ŽwâÊpppp8Npdpp!cpp{pppppppppppppppppyY:¸[ªA¥Bi `ۯǺxp‰pppppp2pppppppppppppppppppppppppppppppppppp¿
I want to extract file directions like "D:\Music\Korn\Untouchables\03 Blame.mp3".
You cannot use a line-oriented scanner to read binary files. You have no guarantee that the binary file even has "lines" delimited by newline characters. For example, what would your scanner do if there were TWO files matching the pattern "D:\.*.mp3" with no intervening newline? You would extract everything between the first "D:\" and the last ".mp3", with all the garbage in between. Extracting file names from a non-delimited stream such as this requires a different strategy.
If i were writing this I'd use a relatively simple finite-state recognizer that processes characters one at a time. When it encounters a "d" it starts saving characters, checking each character to ensure that it matches the required pattern, ending when it sees the "3" in ".mp3". If at any point it detects a character that doesn't fit, it resets and continues looking.
EDIT: If the files to be processed are small (less than 50mb or so) you could load the entire file into memory, which would make scanning simpler.
As was said, since it is a binary file you can't use a Scanner or other character based readers. You could use a regular FileInputStream to read the actual raw bytes of the file. Java's String class has a constructor that will take an array of bytes and turn them into a string. You can then search that string for the file name(s). This may work if you just use the default character set.
String(byte[]):
http://download.oracle.com/javase/1.4.2/docs/api/java/lang/String.html
FileInputStream for reading bytes:
http://download.oracle.com/javase/tutorial/essential/io/bytestreams.html
Use hasNextLine() instead of hasNext() in the while loop check.
while (readF.hasNextLine()) {
String line = readF.nextLine();
//Your code
}