Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
I am quite new to coding in Java and I am trying to make a plugin which creates a character template. The user will type the command /char name . I want it to then check if the command sender's file exists and if so it will write under the field "Name: " in their .dat file. If the file does not exist then it will create a file and write in that field. The only problem I am having is creating and writing and reading from the file. At one point I managed to get it to create the user file and write the name that they set but I couldn't write more as it would write something stupid like "Name: Gender" in the file. I also have no idea how to read from the file as well as it needs to be able to get their set name to change the name tag above their head.
This is an example of the code I am using on the command "/char gender":
if (label.equalsIgnoreCase("char gender")) {
if (args.length < 2) {
sender.sendMessage("/char gender <Male or Female>");
return false;
}
if (args.equals("male")) {
PrintWriter writer1;
try {
writer1 = new PrintWriter("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml", "UTF-8");
writer1.println("Gender: Male");
writer1.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
File file = new File("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml");
}
}
else if (args.equals("female")) {
PrintWriter writer1;
try {
writer1 = new PrintWriter("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml", "UTF-8");
writer1.println("Gender: Female");
writer1.close();
} catch (FileNotFoundException | UnsupportedEncodingException e) {
File file = new File("plugins/Guildplate/PlayerData/" + sender.getName() + ".yml");
}
}
else {
sender.sendMessage("/char gender <male or female>");
}
I am using a .yml file to test if it works because some reason, it will not create the player.dat
You are using the args array incorrectly:
if (args.equals("male"))
else if (args.equals("female"))
A String[] can never be a String so those will always both fail. Assuming the args translates as follows:
"/char gender male" -> new String[]{"/char", "gender", "male"}
You will need to use:
if (args[2].equals("male"))
else if (args[2].equals("female"))
Additionally, your error check should then be:
if (args.length <= 2)
As you'd need 3 arguments to specify it correctly.
The label can not have a space in it therefore:
if (label.equalsIgnoreCase("char gender"))
doesn't work
Related
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 6 years ago.
Improve this question
I'm trying to make a text editor in Java, but I can't seem to get the "open file" feature to work. When I run the code, it only displays the first line of a file. I've tried all of the code snippets from: How to read a large text file line by line using Java?, but it still reads the first line only.
This is what I have tried:
JMenuItem mntmOpen = new JMenuItem("Open");
mntmOpen.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F5, 0));
mntmOpen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if (e.getSource() == mntmOpen) {
int returnVal = fc.showOpenDialog(null);
if (returnVal == JFileChooser.APPROVE_OPTION) {
File file = fc.getSelectedFile();
//This is where a real application would open the file.
Path HI = file.toPath();
try( Stream<String> lines = Files.lines(HI)
){
for( String line : (Iterable<String>) lines::iterator )
{
editorPane.setText(line);
}
}catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
});
Check out this answer here, you should be able to use the section in the while loop. Pretty straight forward run until null which basically states that the buffer will continue to read until the reader sends back a null pointer in which case there is nothing left in the file. If this doesn't work then we can take a look at it again. Also you got downvoted for asking a question without searching for an answer first. https://www.caveofprogramming.com/java/java-file-reading-and-writing-files-in-java.html
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a file that stores Test questions.
"Test.ser"
I want to be able to create files with the same name but with some incrementor appended for each time someone takes the Test to store the Answers.
"Test1.ser"
"Test2.ser"
...
However, I can't think of a way to implement this. A counter could work, but the counter would reset if someone re-ran the program.
Does anyone have an idea how this is possible? Thanks a lot!
EDIT:
int count = 1;
while (searching) {
fileName = survey.name + Integer.toString(count) + ".ser";
f = new File(fileName);
if(f.exists()) {
count++;
} else {
searching = false;
}
} // Proceed to use file name
Can't get it it increment past file_name1.ser
I suggest you use String.format(String, Object...), File.exists() and something like
public static void main(String[] args) {
String fmt = "Test%02d.ser";
File f = null;
for (int i = 1; i < 100; i++) {
f = new File(String.format(fmt, i));
if (!f.exists()) {
break;
}
}
try {
System.out.println(f.getCanonicalPath());
} catch (IOException e) {
e.printStackTrace();
}
}
Edit
As pointed out in the comments, this only retries 100 times. If you want to support more then 100 retries you could write the for loop like,
for (int i = 1;; i++)
An easy way to solve this would be appending the date and the time to your filename.
For example using the format (YYYYMMDD-HHMM):
Test-20141122_2058.ser
Test-20141123_1931.ser
Test-20141123_2157.ser
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 9 years ago.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Improve this question
I have a file dictionary.txt and I need to get that file from the raw folder so I googled around and found this:
Here's an example:
"android.resource:///"+getPackageName()+ "/" + R.raw.dictionary;
but it did not work, Any idea?
Edit:
here is what i am doing
for(String line: FileUtils.readLines(file))
{
if(line.toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
You can get an input stream on a raw resource by using:
getResources().openRawResource(R.raw.dictionary);
EDIT:
From your edit, there really isn't a reason as to why you would specifically need the file rather than just using the input stream available from the openRawResource(int id) method...just use an existing java class http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner%28java.io.InputStream,%20java.lang.String%29.
Scanner scanner = new Scanner(getResources().openRawResource(R.raw.dictionary));
while(scanner.hasNextLine()){
{
if(scanner.nextLine().toLowerCase().equals(b.toLowerCase()))
{
valid = true;
}
}
}
Unfortunately you can not create a File object directly from the raw folder. You need to copy it in your sdcard or inside the application`s cache.
you can retrieve the InputStream for your file this way
InputStream in = getResources().openRawResource(R.raw.yourfile);
try {
int count = 0;
byte[] bytes = new byte[32768];
StringBuilder builder = new StringBuilder();
while ( (count = is.read(bytes,0 32768) > 0) {
builder.append(new String(bytes, 0, count);
}
is.close();
reqEntity.addPart(new FormBodyPart("file", new StringBody(builder.toString())));
} catch (IOException e) {
e.printStackTrace();
}
EDIT:
to copy it over to internal storage:
File file = new File(this.getFilesDir() + File.separator + "fileName.ext");
try {
InputStream inputStream = resources.openRawResource(R.id._your_id);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte buf[]=new byte[1024];
int len;
while((len=inputStream.read(buf))>0) {
fileOutputStream.write(buf,0,len);
}
fileOutputStream.close();
inputStream.close();
} catch (IOException e1) {}
Now you have a File that you can access anywhere you need it.
Place the file in the assets folder and open it like this
getResources().getAssets().open("dictionary.txt");
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I'm creating a sport prediction game for my Grade 11 year and I'm having issues writing data to a text file. I'm using NetBeans 7.3.1. I'm using a button where every time it is pressed data entered by the user must be written to the text file. The text file is empty in the beginning and I need to add data to it. After the first click on the button the data keep rewriting itself and the new data is not added. It needs to be in a new line each time. Thank you very much. Some coding would be awesome!
I just did a quick search for appending to a file (usually a good thing to do): this question seems to be what your looking for.
I haven't tested this, but this should work:
private boolean appendToFile(String fileName, String data, String lineSeparator)
throws IOException {
FileWriter writer = null;
File file = new File(fileName)
if (!file.exists()) {
file.createNewFile();
}
try {
writer = new FileWriter(fileName, true);
writer.append(data);
writer.append(lineSeparator);
} catch (IOException ioe) {
return false;
} finally {
if (writer != null) {
writer.close();
}
}
return true;
}
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java - Find a line in a file and remove
I have a code that Get id number and search for its records, if exist, display it.
I want if found, delete it record.
One solution for delete a line( a user record) is create another file and copy all lines without found record.
can anyone tell me another solution? (Simple solution)
my BookRecords.txt file is this:
Name Date Number
one 2002 22
two 2003 33
three 2004 44
four 2005 55
my Code to find :
String bookid=jTextField2.getText();
File f=new File("C:\\BookRecords.txt");
try{
FileReader Bfr=new FileReader(f);
BufferedReader Bbr=new BufferedReader(Bfr);
String bs;
while( (bs=Bbr.readLine()) != null ){
String[] Ust=bs.split(" ");
String Bname=Ust[0];
String Bdate=Ust[1];
String id = Ust[2];
if (id.equals(bookid.trim())
jLabel1.setText("Book Found, "+ Bname + " " + Bdate);
break;
}
}
}
catch (IOException ex) {
ex.printStackTrace();
}
please help to delete a Line(a Record)
Thanks.
Working on a single text file is - uhm - a bit strange. But I would recommend, that you create a new text file (output):
PrintWriter out = new PrintWriter(new FileWriter("output.txt"));
Only write the lines that don't match the book's ID.
while (...) {
...
if (!id.equals(bookid.trim())) {
out.println(bs);
}
}
out.close();
Later you can rename the file, if you like.
replace the entire line in the text file with a backspace character when found
\b