I am currently codding a Java application for me and my friends and I am encoutering a big problem...
When I try to read a txt file, it prints the lines with strange caracters and each caracter is separed by a white space.
I tryed with multiple txt files in different folders and I prints the same thing everytime... (I tryed to make the code with a Scanner and a BufferedReader and it is still the same problem
Here is my code:
BufferedReader br = new BufferedReader(new FileReader(_file));
String website = "";
String username = "";
String password = "";
int usedTimes = 0;
String currentLine;
while ((currentLine = br.readLine()) != null) {
if(currentLine.startsWith("Web Site")) website = currentLine.split(":")[1];
else if(currentLine.startsWith("User Name")) username = currentLine.split(":")[1];
else if(currentLine.startsWith("Password")) password = currentLine.split(":")[1];
else if(currentLine.startsWith("Password Use Count"))
{
usedTimes = Integer.parseInt(currentLine.split(":")[1]);
passwords.add(new Password(website, username, password, usedTimes));
website = "";
username = "";
password = "";
usedTimes = 0;
}
}
br.close();
Here is an example output: (I cant copy/paste the output so I place a picture)
So if anyone of you knows the answer, please tell me it would be great !
Thank you really much for reading this until here !
Julien.
It may be encoding issue. You have to check text file encoding, and then you have to try like this:
BufferedReader r = new BufferedReader(new InputStreamReader("ISO-XXXXX"))
Related
I am trying to read parts of a text file with the format
John Smith
72
160
The first line being the name (string), and the second and third lines being height and weight (both ints). However, I cannot find a way to store each of these into their own variables, instead I can only figure out how to store the whole thing into one variable and print it. This is the code that I have as of now
try
{
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
StringBuffer stringBuffer = new StringBuffer();
String line;
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line);
stringBuffer.append("\n");
}
fileReader.close();
System.out.println(stringBuffer);
}
In this part
stringBuffer.append(line);
stringBuffer.append("\n");
I was thinking of trying to add a part in the middle of both those lines that stored a variable, but it did not seem possible. I also thought of using a for loop and using that to my advantage somehow, but could not figure out a way to do it with that either.
Is there any possible way to do this that I do not know about? Thank you
Reading and parsing a text file in Java has been getting easier in every new version. You can try the following way:
List<String> lines = Files.lines(Paths.get("person.txt")).collect(Collectors.toList());
String name = lines.get(0);
Integer height = Integer.parseInt(lines.get(1));
Integer weight = Integer.parseInt(lines.get(2));
File file = new File("person.txt");
FileReader fileReader = new FileReader(file);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String firstline = bufferedReader.readLine();
String secondline = bufferedReader.readLine();
String thirdline = bufferedReader.readLine();
fileReader.close();
i am writing a java program to read a file and print output to another string variable.which is working perfectly as intended using is code.
{
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
}
System.out.println(key); //this prints contents of .txt file
}
this prints whole text in the file.But i want to only print the lines till word END is encountered in file.
example: if input.txt file contains following text : this test file END extra in
it should print only :
this test file
Just do a simple indexOf to see where it is and if it exists in the line. If the instance is found one option would be using substring to cut off everything up until the index of the keyword. For a bit more control though try using java regular expressions.
String key = "";
FileReader file = new FileReader("C:/Users/raju/Desktop/input.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while ((line = reader.readLine()) != null && line.indexOf("Keyword to look for") == -1)
key += line;
System.out.println(key);
I am not sure why it needs to be any more complicated than this:
BufferedReader re = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String str = re.readLine();
if (str.equals("exit")) break;
// whatever other code.
}
You can do it in many ways. one of them is using indexOf method to specify the start index of "END" in input and then using subString method.
for more information, read documentation of String calss. HERE
This will work for your issue.
public static void main(String[] args) throws IOException {
String key = "";
FileReader file = new FileReader("/home/halil/khalil.txt");
BufferedReader reader = new BufferedReader(file);
String line = reader.readLine();
while (line != null) {
key += line;
line = reader.readLine();
} String output = "";
if(key.contains("END")) {
output = key.split("END")[0];
System.out.println(output);
}
}
You have to change your logic to check if the line contains "END".
If END not found in a line, add the line to key stringin your program
If yes, split that line into word array, read the line till you encounter the word "END" and append it to your key string. Consider using Stringbuilder for key.
while (line != null) {
line = reader.readLine();
if(!line.contains("END")){
key += line;
}else{
//Note that you can use split logic like below, or use java substring
String[] words = line.split("");
for(String s : words){
if(s.equals("END")){
return key;
}
key += s;
}
}
}
I'm trying to extract device name for android using "adb devices" command ..
successfully by using this method I got that:
public void newExec() throws IOException, InterruptedException, BadLocationException{
String adbPath = "/Volumes/development/android-sdk-macosx/tools/adb";
String cmd = adbPath+" "+"devices";
Process p;
p = Runtime.getRuntime().exec(cmd);
p.waitFor();
String line;
BufferedReader err = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((line = err.readLine()) != null) {
System.out.println(line);
}
err.close();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line=input.readLine()) != null) {
//printing in the console
System.out.println(line);
}
input.close();
}
The output is:
List of devices attached
192.168.56.101:5555 device
I tried to get only the device name out of this output which is:
192.168.56.101:5555
I used split in many ways such as:
String devices = "List of devices attached";
System.out.println(line.split(devices);
but this is not working at all!
I don't want a static way, but dynamic one. I mean if the device name changed or there are more than one listed devices I want a way to just give the device name only.
is there a way of that?
Sorry if the question is not that clear, I'm little new to Java :)
You can try below code :
The next line of output of adb devices is separated by tabs, so we have to use "\t" as argument.
List<String> deviceList = new ArrayList<String>();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while ((line = input.readLine()) != null) {
if (line.endsWith("device")) {
deviceList.add(line.split("\\t")[0]);
}
}
for (String device : deviceList) {
System.out.println(device);
}
Use the below code (Note: it only work if the string output is same every time)
String devices = "List of devices attached 192.168.56.101:5555 device";
String[] str = devices.split(' '); //spliting the string from space
System.out.println(str[4]);
Output:
192.168.56.101:5555
Hope this will help you.
I am not much familiar with Android programming but to me this sounds like a simple string parsing issue than being specific to android. Anyways, my 2 cents here. You could try parsing the lines only if it ends with
String line;
List<String> devices = new ArrayList<String>();
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
while((line=input.readLine())!=null){
//printing in the console
System.out.println(line);
if (!line.endsWith("device")) {
//skip if it does not ends with suffix 'device'
continue;
}
else {
//parse it now
String[] str = line.split(" ");
devices.add(str[0]);
}
}
Appears that you are using the String split() method wrong.
String devices = "List of devices attached";
System.out.println(line.split(devices);
An example of use:
String[] ss = "This is a test".split("a");
for (String s: ss )
System.out.println(s);
OUTPUT
This is
test
The parameter of split(String regex) must be a Regular Expression (regex).
Also, you could use a StringTokenizer class, or a Scanner class. These classes have more options to tokenize.
I have a File that COntains Strings in This Format:
ACHMU)][2:s,161,(ACH Payment Sys Menus - Online Services)][3:c,1,(M)][4:c,1,(N)]
ACLSICZ)][2:s,161,(Report for Auto Closure)][3:c,1,(U)][4:c,1,(N)]
ACMPS)][2:s,161,(Account Maintenance-Pre-shipment Account)][3:c,1,(U)][4:c,1,(N)]
ACNPAINT)][2:s,161,(Interest Run For NPA Accounts)][3:c,1,(U)][4:c,1,(N)]
I need to Split the String so that I have the data in this Format:
ACHMU (ACH Payment Sys Menus - Online Services)
ACLSICZ (Report for Auto Closure)......
Basically, I want to remove the ")[2:s,161," part and the "][3:c,1,(M)][4:c,1,(N)]" at the end. Will Splitting the String Help Me? The following Method has already failed:
FileInputStream fs = new FileInputStream(C:/Test.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String str;
while((str = br.readLine()) != null){
String[] split = str.Split(")[2:s,161,")
}
Please Help me get the Junk in the middle and at the end.
The straight-forward way, use substring() and indexOf():
String oldString = "ACHMU)][2:s,161,(ACH Payment Sys Menus - Online Services)][3:c,1,(M)][4:c,1,(N)]";
String firstPart = oldString.substring(0, oldString.indexOf(")")); // ACHMU
String secondPart = oldString.substring(oldString.indexOf("(")); // (ACH Payment Sys Menus - Online Services)][3:c,1,(M)]
String newString = firstPart + " " + secondPart.substring(0, secondPart.indexOf(")") + 1); // ACHMU (ACH Payment Sys Menus - Online Services)
System.out.print(newString);
OUTPUT:
ACHMU (ACH Payment Sys Menus - Online Services)
You can use
str.replaceFirst("(.*?)\\)\\].*?(\\(.*?\\))\\].*", "$1 $2");
FileInputStream fs = new FileInputStream(C:/Test.txt);
BufferedReader br = new BufferedReader(new InputStreamReader(fs));
String str;
String newStr;
String completeNewStr="";
while((str = br.readLine()) != null)
{
newStr = str.replace(")][2:s,161,"," ");
newStr = str.replace("][3:c,1,(M)][4:c,1,(N)]","");
completeNewStr+=newStr;
}
// completeNewStr is your final string
If the string that you want to replace is always "[2:s,161," , replace it with a empty string or space if that's acceptable. Similarly, for the other string as well.
str.replace("[2:s,161,", '');
I need to read alot of files and insert the data into Ms sql.
Got a file, it looks the texts are separated by //t.
Split does not do the job, I have even tried with "//s+" as you can see in the code below
public void InsetIntoCustomers(final File _file, final Connection _conn)
{
conn = _conn;
try
{
FileInputStream fs = new FileInputStream(_file);
DataInputStream in = new DataInputStream(fs);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
//String strline contains readline() from BufferedReader
String strline;
while((strline = br.readLine()) != null)
{
if(!strline.contains("#"))
{
String[] test = strline.split("//s+");
if((tempid = sNet.chkSharednet(_conn, test[0] )) != 0)
{
// do something
}
}
}
// close BufferedReader
br.close();
}
I need to know where in my String[] the data is placed in a file with 500k lines. But my Test[] get length 1 and all data from readline are on place 0.
Do I use split wrong ?
Or are there other places I need to look?:
// Mir
haha - Thank you so much - why the hell didnt I see that myself.
yeah ofc. iam using \s+ at all other files.
but thank for pointing it out.
The correct regex is \\s+, with back-shashes instead of forward-slashes.
You could have still tried with \\t