Formatting the output in desired way - java

the following method produces an output.
The only problem with this code is that after the end of report, it adds two extra lines to the file, while the need is only of one empty line.
i have tried various combinations but uanble to proceed.
Can anybody help here?
private static void save_player_info(String[][] data, String player) {
player=player.toLowerCase();
try {
PrintWriter printWriter= new PrintWriter(new File("out4.txt"));
for(int row=1;row<data.length;row++){
String playerName=data[row][0].toLowerCase();
if(playerName.indexOf(player)!=-1){
String[] fields=data[0];
String[] values=data[row];
for (int i=0;i<fields.length;i++){
printWriter.printf("%21s : %s\n",fields[i],values[i]);
}
printWriter.print("\n");
}
}
printWriter.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Instead of unconditionally adding a blank line after the inner for loop, you should conditionally add a blank line before the inner for loop, if not the first time.
Also, you should use %n in printf for the newline, and println() for the blank line. And you should put the close() in a finally block, or use try-with-resources. Showing finally block solution here for Java version independence.
PrintWriter printWriter= new PrintWriter(new File("out4.txt"));
try {
boolean first = true;
for(int row=1;row<data.length;row++){
String playerName=data[row][0].toLowerCase();
if(playerName.indexOf(player)!=-1){
String[] fields=data[0];
String[] values=data[row];
if (first)
first = false;
else
printWriter.println();
for (int i=0;i<fields.length;i++){
printWriter.printf("%21s : %s%n",fields[i],values[i]);
}
}
}
} finally {
printWriter.close();
}

Since you are using new line in
printWriter.printf("%21s : %s\n",fields[i],values[i]);
So you can skip
printWriter.print("\n");

You can wrap an if statement around the line which prints a newline character to check if row is less than data.length. Also, you can use println() instead of print("\n").
for(int row=1;row<data.length;row++){
...
if(row < data.length - 1){
printWriter.println();
}
}

Related

while loop and printwriter only writes one line to file

I have made a code of which gets a bunch of data from different files in a folder, I have then made sure to only look for a certain kind of word in the files. Then I have made sure the code prints out the results in the console.
All the things I have done up till now works perfectly, but here comes the issue. I want the code to also print/write the information to a .txt file. This sort of works, but it only prints one of the many lines from the different files. I am completely sure that there are more that one as the console print shows at least 20 different lines containing the right word.
I am not completely sure where I have gone wrong, I have also tried to add the .flush(); right before the .close(); but it still wont work. I have also tried to add the pToDocu.close(); underneath the sc.close();, but that doesn't work either, as that doesn't even write anything, that just creates a blank file.
So in short the code is supposed to write a bunch of lines, but it only writes one.
public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#"))
{
System.out.println(s);
pTD.println(s);
pTD.close();
}
}
sc.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
UPDATE
I have changed the code to now have the pTD.close(); outside of the while loop like seen below. Only issue is that the file which is created now is blank, it has no information inside it.
public static void lisFilesF(final File folderV) throws IOException {
PrintWriter pTD = new PrintWriter("eFile.txt");
for (final File fileEntry : folderV.listFiles()) {
if (fileEntry.isDirectory()) {
listFilesForFolder(fileEntry);
} else {
System.out.println(fileEntry.getName());
try {
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#"))
{
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
You are closing the file (pTD) after the first time you write to it. You should extract the close() call from the loop and move it after it:
Scanner sc = new Scanner(fileEntry);
while (sc.hasNextLine()) {
String s = sc.nextLine();
if(s.contains("#")) {
System.out.println(s);
pTD.println(s);
}
}
sc.close();
pTD.close();
Remove
pTD.close();
from your while loop. You close your Print Writer after the first write
It looks like you want to commit ALL of those records to your PrintWriter. Therefore, your pTD.close(); needs to be outside of your for loop, since you declared the PrintWriter before your for loop.

String to Text - Line Break instead of comma

I need help before I'm totally despaired :D
As you will see I tried it in different ways even if there are just a really few differences. My problem is that I have a string which I want (or have) to output. This means I need it in a text file. Not that big problem, eh? But the actual problem is that I want line breaks instead of commas. I know I could just replace them after the file is written but it's just unnecessary when there is another way.
The Output looks like this
[/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus,
/rechtschreibung/_Ndrangheta, ....]
I want it to look like this
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Anyway even when I don't need this method later because I will store this and some other information into a database like sql. It will help me to build up the program step by step and learn some more Java ;)
So here is my code snippet
BufferedWriter bw = null;
//PrintWriter out
//= new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
try {
bw = new BufferedWriter(new FileWriter("bfwr.txt"));
bw.write(test5.getWoerterListe().toString());
bw.newLine();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
try {
PrintWriter out = new PrintWriter(new FileWriter("prwr.txt"));
out.print(test5.getWoerterListe());
out.close();
System.out.printf("Testing String");
} catch (IOException e) {
e.printStackTrace();
}
*/
/*
try {
FileWriter test10 = new FileWriter("test.txt");
test10.write(test5.getWoerterListe().toString());
test10.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
*/
Please be nice to me :D
Assistance appreciated =)
EDIT #1
Code directly before first one.
Oberordner test2 = new Oberordner("http://www.duden.de/definition");
Unterordner test3 = new Unterordner(test2.getOberOrdner());
WoerterListe test5 = new WoerterListe(test3.getUnterOrdnerURL());
test5.setWoerterListe();
and from WoerterListe.java the really end part
public ArrayList<String> getWoerterListe(){
return WoerterListe;
}
Additional Information: the string is not stored in the code because there are tenthousands of words like '/rechtschreibung/*'
By the way the language here is german unfortunately I have to use german words =(
I'm not a Java developer and you didn't state what getWoerterListe() returns, but here's my guess.
getWoerterListe() probably return a list of strings, and the default behaviour of toString() in this case is to convert the list to comma seperated values. So instead of calling toString() on the list, loop through it and write out each line followed by a carriage return (or whatever Java uses to end lines).
Code:
String s = "[/rechtschreibung/_n, /rechtschreibung/_nauf, "
+ "/rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....]";
String srp = s.replaceAll("\\[|\\]|\\.+" ,"");
String[] sp = srp.split(",");
for (int i = 0; i < sp.length; i++) {
System.out.println(sp[i].trim());
}
Output:
/rechtschreibung/_n
/rechtschreibung/_nauf
/rechtschreibung/_naus
/rechtschreibung/_Ndrangheta
Explanation:
I assumed [/rechtschreibung/_n, /rechtschreibung/_nauf, /rechtschreibung/_naus, /rechtschreibung/_Ndrangheta, ....] is a String. I removed all uncessary character like [ , ] , and any number of . form it. After that, I splited by , and print each element of splited string on the output.

in android, trying to find text loaded from an asset file

so what I am trying to accomplish is check a file to see if a word in the file matches the customers input.
I am attaching the code from when the button is clicked and what its supposed to do. Where its failing, or basically not doing it right, is where its supposed to check to see if it is in the list.
*CODE*
btn1.setOnClickListener(new OnClickListener() { // listen for when i click
public void onClick(View v) {
btn1.setText("yeah");
theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input
System.out.println("before i read file theirpass =s "+ theirpass);
System.out.println("before i read file checking =s "+ checking);
readFile(); // read the accouts dude
tv1.setText("i pressed the button");// test to make sure button pressing works
System.out.println("after reading. theirpass =s " + theirpass);
System.out.println("after i read file. checking =s "+ checking);
}// end on click
}); //end listener
}// end oncreate
public void readFile() {
BufferedReader reader = null;
try {
reader = new BufferedReader(
new. InputStreamReader(getAssets().open("account.txt")));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();// reading each line.
while (mLine != null) {
//process line
mLine = reader.readLine();
if. (mLine.matches(theirpass)) { // when an. account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking = theirpass; //trying to set vale of. checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
}// end loop
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
Log.d("Catch buffer","i failed the catch in finally for reading lines");
}
}
}//end buffer reader
Toast.makeText(this,checking,Toast.LENGTH_LONG).show(); //test to get. value of cheking, keeps coming up blank- no text
if (checking == theirpass) {
btn1.setText("its there");//test to see if the if statment works
System.out.println("i just checked if its there");//another test
}
}
}
To help with code
![helping with code again][2]
new Code
if (mLine.equals(theirpass)) { // when an account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking.equals(theirpass); //trying to set vale of checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
mLine = reader.readLine();
} //end buffer reader
value of theirpass
//the value if theirpass is shown below it's in the onClick method
theirpass = edt1.getText().toString().toLowerCase(); // set theirpass = to text boxs input
Try printing the mLine value right after "mLine = reader.readLine();" to know what you read from the file.
But I guess your biggest problem is the misuse of the "matches" function. Matches uses reg ex (http://developer.android.com/reference/java/lang/String.html#matches(java.lang.String) ) .
Instead you should use ".equals" or read this for a good use of string comparison.
You should also change your while loop the this:
// do reading, usually loop until end of file reading
String mLine = reader.readLine();// reading each line.
while (mLine != null) {
//process line
if. (mLine.matches(theirpass)) { // when an. account is found stop reading
System.out.println("cheking mLine"+ mLine);
checking = theirpass; //trying to set vale of. checking to theirpass
Log.d("if statement in mline",checking);
mLine=null;// trying to stop the loop
}//end if
mLine = reader.readLine();
}// end loop
Because you read a line, go into your while, read a new line and have now skipped the first line of the file.

Avoiding null indexes in my array

I am trying to write a new document based on the Objects I have in my side2[] array.
Now unfortunately, some indexes are null in this array, and when it hits one of them, it just gives me a NullPointerException. This array has 10 indexes, but in this case not all of them are needed. I have tried the try catch statement in hopes of continuing after it comes across a null, but it still stops execution and doesn't write a new document.
The stack (srail) that is part of the object contains the data I want to print out.
Here is my code:
// Write to the file
for(int y=0; y<=side2.length; y++)
{
String g = side2[y].toString();
if(side2[y]!=null){
while(!side2[y].sRail.isEmpty())
{
out.write(side2[y].sRail.pop().toString());
out.newLine();
out.newLine();
}
out.write(g);
}
}
//Close the output stream/file
out.close();
}
catch (Exception e) {System.err.println("Error: " + e.getMessage());}
The problem is that the code calls toString() on the side2[y] object before checking it for null. You can skip null objects by adding a condition at the top of the loop, like this:
for(int y=0; y<=side2.length; y++) {
if(side2[y] == null) {
continue;
}
String g = side2[y].toString();
// No further checks for null are necessary on side2[y]
while(!side2[y].sRail.isEmpty()) {
out.write(side2[y].sRail.pop().toString());
out.newLine();
out.newLine();
}
out.write(g);
}

I need to contain all matches of a Regex into a text file; I'm new to java programming

I'm trying to contain all matches found into a text document, I have been banging my head on my desk for the past 3 hours and figured it would be time I asked for help.
My current issue is with the List<String> and I'm not sure if it because the information entered is wrong or if it's my file print methods. It does not print to file and with other means of printing such as writer.println(returnvalue) and even then, it still only displays one of the matches and not all, I do have the matches appearing in console just to make sure they are showing and they are.
Edit2: Sorry this would be my first question on stackoverflow, I guess my question is How would you print all the data from a list array to a text file?
Edit3: My newest problem is printing out all matches i am currently stuck printing out the last match, any advice?
public static void RegexChecker(String TheRegex, String line){
String Result= "";
List<String> returnvalue = new ArrayList<String>();
Pattern checkRegex = Pattern.compile(TheRegex);
Matcher regexMatcher = checkRegex.matcher(line);
int count = 0 ;
FileWriter writer = null;
try {
writer = new FileWriter("output.txt");
} catch (IOException e1) {
e1.printStackTrace();
}
while ( regexMatcher.find() ){
if (regexMatcher.group().length() != 0){
returnvalue.add(regexMatcher.group());
System.out.println( regexMatcher.group().trim() );
}
for(String str: returnvalue) {
try {
out.write(String.valueOf(returnvalue.get(i)));
writer.write(str);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Get the for out of while. You want to write to the file only after all matches have been added to the list. The for-each block needs some modifications as well.
The for-each construct gives you values from iteration over the collection. You need not obtain the values again using an index.
Try this:
while (regexMatcher.find()) {
if (regexMatcher.group().length() != 0) {
returnvalue.add(regexMatcher.group());
System.out.println(regexMatcher.group().trim());
}
}
try {
for (String str : returnvalue) {
writer.write(str + "\n");
}
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}

Categories

Resources