Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I am working on the password login portion of a class project. Nothing fancy. User, or role will be an int and password is a String. I am just using a simple encryption for now. The problem I am having is while reading the file I am getting an input mismatch. I have done something similar in the past that required me to read ints and Strings and did not have any problems. But I just cannot figure out what is going wrong in this case. Any help as to why I am getting this error would be greatly appreciated. I am using while(inputStream.hasNextLine()) then read the int and then the String I have tried hasNextInt and hasNext and keep getting the same error.
public void readFile(){
Scanner inputStream = null;
try {
inputStream = new Scanner (new FileInputStream("login.txt"));
}catch (FileNotFoundException e) {
e.printStackTrace();
}
if(inputStream != null){
while (inputStream.hasNextLine()){
int luser = inputStream.nextInt();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count ++;
}
inputStream.close();
}
}
Try reading it as a String and converting the string to an int
while (inputStream.hasNextLine()) {
Integer luser = Integer.parseInt(inputStream.nextLine());
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
count++;
}
But you need to make sure your file has your data in the exact format as below
12342
password
It's hard to say without knowing what error it is that you are getting, but my guess is that it is because you are not reading the entire file.
Your file probably looks like this:
1\r\n
password\r\n
When you call nextInt() it reads the int, but doesn't advance past the first \r\n so when you call nextLine() it reads to the end of the line so all you get is \r\n. You need to read past the first \r\n and then read the password.
Try
int luser = inputStream.nextInt();
inputStream.nextLine();
String lpass = inputStream.nextLine();
newFile[count] = new accessNode(luser, lpass);
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am developing a program that takes input from the console. So far it has been no problem reading input that consists of one line of input from the console. But the program does not work when it is supposed to read multiple lines. How can i improve the readInput method to read multiple lines of input and the return a single String containing all of the input from different lines.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
String input = inputstream.readLine();
return input;
}
So when you write String input = inputstream.readLine() This reads one line at a time,
As you are taking input from the user there would not be any null cases even if the user clicks enter, You need to check for the length of the input string, If it is 0 then break from the while loop.
But this isn't the case when you are reading from a file or other source you need to check whether the input is null or not.
Hope this could help you.
private String readIntput() throws IOException {
BufferedReader inputstream = new BufferedReader(new InputStreamReader(System.in));
StringBuilder finalString = new StringBuilder();
String input = inputstream.readLine();
while(true){
finalString.append(input);
input=inputstream.readLine();
if(input.length() == 0){
break;
}
}
br.close();
return finalString;
}
Input:
hi hello
how are you
Am fine
Output:
hi hellohow are youAm fine
I'm currently writing my project for school in which requires me to read and write to txt files. I can read them correctly but I can only write to them at the end from an appended FileWriter. I would like to be able to overwrite things in my txt files on line numbers by first deleting the data on the line and then writing in the new data. I attempted to use this method...
public void overWriteFile(String dataType, String newData) throws IOException
{
ReadFile file = new ReadFile(path);
RandomAccessFile ra = new RandomAccessFile(path, "rw");
int line = file.lineNumber(path, dataType);
ra.seek(line);
ra.writeUTF(dataType.toUpperCase() + ":" + newData);
}
but I believe that the seek method moves along in bytes rather than line numbers. Can anyone help. Thanks in advance :)
P.S. the file.lineNumber method returns the exact line that the old data was on so I already have the line number that needs to be written to.
EDIT: Soloution found! Thanks guys :) I'll post the soloution below if anyone is interested
public void overWriteFile(String dataType, String newData, Team team, int dataOrder) throws IOException
{
try
{
ReadFile fileRead = new ReadFile(path);
String data = "";
if(path == "res/metadata.txt")
{
data = fileRead.getMetaData(dataType);
}
else if(path == "res/squads.txt")
{
data = fileRead.getSquadData(dataType, dataOrder);
}
else if(path == "res/users.txt")
{
data = fileRead.getUsernameData(dataType, dataOrder);
}
else if(path == ("res/playerdata/" + team.teamname + ".txt"))
{
//data = fileRead.getPlayerData(dataType, team.teamname, dataOrder);
}
BufferedReader file = new BufferedReader(new FileReader(path));
String line;
String input = "";
while((line = file.readLine()) != null)
{
input += line + '\n';
}
input = input.replace(dataType.toUpperCase() + ":" + data, dataType.toUpperCase() + ":" + newData);
FileOutputStream out = new FileOutputStream(path);
out.write(input.getBytes());
}
catch(Exception e)
{
System.out.println("Error overwriting file: " + path);
e.printStackTrace();
}
}
A quick and dirty solution would be to use the Files.readAllLines and Files.write methods to read all lines, change the one you want to change, and overwrite the whole file:
List<String> lines = Files.readAllLines(file.toPath());
lines.set(line, dataType.toUpperCase() + ":" + newData);
Files.write(file.toPath(), lines); // You can add a charset and other options too
Of course, that's not a good idea if it's a very big file. See this answer for some ideas on how to copy the file line by line in that case.
Regardless of how you do it, though, if you are changing the byte length of the line, you will need to rewrite the whole file (AFAIK). RandomAcessFile allows you to move around the file and overwrite data, but not to insert new bytes or removes existing ones, so the length of the file (in bytes) will stay the same.
Here is a link to a question just like this with a great answer:
I want to open a text file and edit a specific line in java
Basically, you can't just edit that line, unless it'll be the exact same length.
Instead, you'll want to copy over every line, and then when you reach the line number of the line you want to change, instead of copying over the old line, just put in your new line.
The link I gave you has a great example on how to do this.
I hope this helps...if not, let me know, and I'll elaborate further on the post. Good luck :)
I have a question about the snippet of code which I have underneath. I have a file called FILNAVN which is a file where the info the program needs is located. The first line of said file is a row of integers which I will only need read once. Will the code acutally do this? I ask because I haven't programmed the code inside the while-loop yet, and I could actually needs some tips as to how to do this as well :P
try{
Scanner leseFraFila= new Scanner(new File(FILNAVN)).useDelimiter(";");
int maaned=leseFraFila.nextInt();
int aar=leseFraFila.nextInt();
int totalFortjeneste=leseFraFila.nextInt();
int totaltAntallMaaneder=leseFraFila.nextInt();
int maanedsleieVanligHybel=leseFraFila.nextInt();
int maanedsleieToppHybel=leseFraFila.nextInt();
while(FILNAVN.hasNext()){
//Here is where I will probably use:
//String linje=leseFraFila.nextLine()
//linje.split(";");
//String .... =
//int ....=
}
}catch(IOException e){
System.out.print(e);
}
Here is a short, and simply solution to your problem:
static String readFile(String path, Charset encoding) throws IOException
{
byte[] encoded = Files.readAllBytes(Paths.get(path));
return encoding.decode(ByteBuffer.wrap(encoded)).toString();
}
All you have to do now is get the information to a string:
String readContent = readFile("test.txt", StandardCharsets.UTF_8);
OR you can use the defaultCharset().
All credit goes to erickson at his very informative post here
I'm trying to basically make a simple Test Generator. I want a button to parse a text file and add the records to my database. The questions and answers are in a text file. I have been searching the net for examples but I can't find one that matches my situation.
The text file has header information that I want to ignore up until the line that starts with "~ End of Syllabus". I want "~ End of Syllabus" to indicate the beginning of the questions. A couple of lines after that look for a line with a "(" in the seventh character position. I want that to indicate the Question Number line. The Question Number line is unique in that the "(" is in the seventh character position. I want to use that as an indicator to mark the start of a new question. In the Question Number line, the first three characters together "T1A" are the Question Group. The last part of the T1A*01* is the question number within that group.
So, as you can see I will also need to get the actual question text line and the answer lines as well. Also typically after the four Answer lines is the Question Terminator indicated by "~~". I don't know how I would be able to do this for all the questions in the text file. Do I keep adding them to an array String? How would I access this information from the file and add it to a database. This is very confusing for me and the way I feel I could learn how this works is by seeing an example that covers my situation. Here is a link to the text file I'm talking about:http://pastebin.com/3U3uwLHN
Code:
public static void main(String args[]) {
String endOfSyllabus = "~ End of Syllabus";
Path objPath = Paths.get("2014HamTechnician.txt");
String[] restOfTextFile = null;
if (Files.exists(objPath)){
File objFile = objPath.toFile();
try(BufferedReader in = new BufferedReader(
new FileReader(objFile))){
String line = in.readLine();
List<String> linesFile = new LinkedList<>();
while(line != null){
linesFile.add(line);
line = in.readLine();
}
System.out.println(linesFile);
}
catch(IOException e){
System.out.println(e);
}
}
else{
System.out.println(
objPath.toAbsolutePath() + " doesn't exist");
}
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new A19015_Form().setVisible(true);
}
});
}
Reading a text file in Java is straight forward (and there are sure to be other, more creative/efficient ways to do this):
try (BufferedReader reader = new BufferedReader(new FileReader(path))) { //try with resources needs JDK 7
int lineNum = 0;
String readLine;
while ((readLine = reader.readLine()) != null) { //read until end of stream
Skipping an arbitrary amount of lines can be accomplished like this:
if (lineNum == 0) {
lineNum++;
continue;
}
Your real problem is the text to split on. Had you been using CSV you could use String[] nextLine = readLine.split("\t"); to split each line into its respective cells based on tab separation. But your not, so you'll be stuck with reading each line, and than find something to split on.
It seems like you're in control of the text file format. If you are, go to an easier to consume format such as CSV, otherwise you're going to be designing a custom parser for your format.
A bonus to using CSV is it can mirror a database very effectivly. I.e. your CSV header column = database column.
As far as databases go, using JDBC is easy enough, just make sure you use prepared statements to insert your data to prevent against SQL injection:
public Connection connectToDatabase(){
String url = "jdbc:postgresql://url";
return DriverManager.getConnection(url);
}
Connection conn = connectToDatabase();
PreparedStatement pstInsert = conn.prepareStatement(cInsert);
pstInsert.setTimestamp(1, fromTS1);
pstInsert.setString(2, nextLine[1]);
pstInsert.execute();
pstInsert.close();
conn.close();
--Edit--
I didn't see your pastebin earlier on. It doesn't appear that you're in charge of the file format, so you're going to need to split on spaces ( each word ) and rely on regular expressions to determine if this is a question or not. Fortunately it seems the file is fairly consistent so you should be able to do this without too much problem.
--Edit 2--
As a possible solution you can try this untested code:
try{
BufferedReader reader = new BufferedReader(new FileReader("file.txt")); //try with resources needs JDK 7
boolean doRegex = false;
String readLine;
while ((readLine = reader.readLine()) != null) { //read until end of stream
if(readLine.startsWith("~~ End of Syllabus")){
doRegex = true;
continue; //immediately goto the next iteration
}
if(doRegex){
String[] line = readLine.split(" "); //split on spaces
if(line[0].matches("your regex here")){
//answer should be line[1]
//do logic with your answer here
}
}
}
} catch (IOException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
I am looking for an update function for a custom ROM based tool. I used this code http://www.androidsnippets.com/check-for-updates-once-a-day as a base and soon realized that I couldn't use Dropbox for deployment with that code. So I modified the code to download a version.txt file from dropbox. The file contains a single number (the latest Version Code, in this case 11). I need to read that line and parse the string as an integer to compare with the current versionCode and trigger a download if an update exists.
All the code works, except for parsing the int from the txt file.
Heres my code:
private Thread checkUpdate = new Thread() {
public void run() {
try {
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"BPversion.txt");
StringBuilder text = new StringBuilder();
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
text.append(line);
int curVersion = getPackageManager().getPackageInfo("com.JB15613.BPcolorTool", 0).versionCode;
System.out.println(line);
int newVersion = 0;
System.out.println(line);
try {
newVersion = Integer.parseInt(line);
System.out.println(line);
} catch(NumberFormatException nfe) {
System.out.println("Exception " + nfe);
}
if (newVersion > curVersion) {
mHandler.post(showUpdate);
}
}
} catch (Exception e) {
Log.d("ANDRO_ASYNC", "Caught exception");
}
}
And I get this exception:
Exception java.lang.NumberFormatException: Invalid int: "11"
When I apply breakpoints and run the debugger, it crashes at the parseInt line.
11 looks like a valid int to me!
Any help is greatly appreciated!
line ends CRLF ,so , need call function trim() in String ..
int newVersion = Integer.parseInt(line.trim());
I just want to add to what has already been stated:
Your problem is that your 11 is not able to parse to an int, the underlying root of which is that you are parsing white space as part of your string.
As already stated the trim() method should remove the problem but If you wanted to know what was causing the problem and why this fixes it then that is the reason.
You are not trying to parse "11", you are parsing something like "11 " or " 11" which is a different thing. The spaces from the file you are reading from are being included in your string as it is passed into the parseInt method.
Again, I know this has been answered but I thought this additional information would still be useful.
Try to print the value of line in the logcat or screen or ui.
Check what will be coming.A valid int is coming or any other is coming.
i think line does not cotains valid int.
Exception java.lang.NumberFormatException
The above exception is thrown due to invalid int format or number format.
Check the values of line