I'm creating a log in form in Java and I've added a remember me method to store the log in data in a local text file for future us.
The premise is that once the checkbox is checked, the email and password gets written out to the text file.
Here's the code below:
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
public void rememberMe() throws IOException {
private final ArrayList<String> storage = new ArrayList<String>();
protected String storPass;
protected String storEmail;
storage.add(storEmail);
storage.add(storPass);
FileWriter writer = new FileWriter("local.txt");
for(String i : storage) {
writer.write(i);
System.out.println("We have written " + i);
}
writer.close();
}
with the output being:
We have written EMAILADDRESS
We have written PASSWORD
The data has been removed, but the printing in the foreach look is showing me that it's cycling through the Arraylist correctly.
The local.txt doesn't have any data in it, it's empty before running and empty during and after the program is ran.
Can anybody spot the problem I'm having?
Thanks in advance.
Instead of Using relative path use absolute path like D:\\local.txt. It will work
Try using:
Path locates/creates the file on the system
Then use the Files object to statically write the file using your list.
Path file = Paths.get("local.txt");
Files.write(file, storage, Charset.forName("UTF-8"));
This way you can stay away from writing explicit foreach loop.
here is more on the Files object which is available since java 1.7+
https://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html
Related
the code that i used :
package play;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
public class Play {
InputStream music;
public Play() {
URL url=getClass().getResource("/music/Whitewoods - College Kill Dream.mp3");
System.out.println(url.toString());
try {
FileInputStream fileInputStream=new FileInputStream(new File(url.toString()));
fileInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String args[]) {
new Play();
}
}
the line below int he above code :
System.out.println(url.toString());
prints :
file:/C:/Users/eclipse-workspace/audioboard/bin/music/Whitewoods%20-%20College%20Kill%20Dream.mp3
if i copy this directly and put it in the chrome's url putting box . the file opens but the line :
FileInputStream fileInputStream=new FileInputStream(new File(url.toString()));
gives file not found error.
error stack:
java.io.FileNotFoundException: file:\C:\Users\eclipse-workspace\audioboard\bin\music\Whitewoods%20-%20College%20Kill%20Dream.mp3 (The filename, directory name, or volume label syntax is incorrect)
at java.base/java.io.FileInputStream.open0(Native Method)
at java.base/java.io.FileInputStream.open(FileInputStream.java:213)
at java.base/java.io.FileInputStream.<init>(FileInputStream.java:155)
at play.Play.<init>(Play.java:17)
at play.Play.main(Play.java:26)
thankyou for the help.
You can use the File constructor File(URI uri) transforming your URL url to URI and passing it as an argument for the File constructor like below:
File file = new File(url.toURI());
The file: bit makes what you see not actually a file path, but a URL.
URL has the toFile() method which is closer to what you want, but still isn't what you're actually looking for, which is getResourceAsStream:
The appropriate way to call getResource/getResourceAsStream, is Play.class.getResource, not getClass().getResource. A minor nit; the getClass() variant is non-idiomatic, and strictly worse/less readable: If Play is ever subclassed, it breaks, whereas Play.class.getResource would not. Even if it isn't relevant, better to use the style that is more idiomatic and the right answer is strictly more scenarios.
Generally, if you convert the resource you get into a file you've messed up; the point of getResource is to give you resources from the same place your classes are found, and they need not be files. They could be entries in a jar (which aren't, themselves, files, and cannot be accessed directly either as a java.io.File or as a java.nio.path.Path), pulled in over the network, generated on the fly - anything goes, that's the point of the abstraction. In this case, you're taking your file and immediately turning that into an InputStream. Don't do that - the getResource abstraction can do this.
Like all resources, you can't just open an inputstream like this. You need to ensure it is closed as well, regardless of what happens. Use try-with-resources to ensure this.
Putting it all together:
String songName = "Whitewoods - College Kill Dream.mp3";
try (var in = Play.class.getResourceAsStream("/music/" + songName)) {
// .... do something with 'in' here. It is an InputStream.
}
No need to close it; the try construct will take care of it for you. Doesn't matter how code 'exits' those braces (by running to the end of it, via return or some other control flow, or via an exception) - that inputstream will be closed.
I'm trying to create an ArrayList of pre-existing text files (basically take a folder of text files that are already saved on my computer and plug them into an ArrayList) so that I can iterate over them and send matching pairs of text files to another program (a separate java program) for data analysis. Is it possible to create an ArrayList of text files the way I want to?
Ever since the java.nio package was introduced, this has become simple enough, especially with Java 8 streams:
Files.walk(new File("/your/base/dir").toPath()) // stream of all files inside base folder
.filter(p->p.getFileName().endsWith(".txt")) // limit to .txt files
.map(Path::toAbsolutePath) // convert to absolute pathy
.forEach(System.out::println); // print
See: Files.walk(path, option...)
In apache commons-io, there is a class called FileUtils which will return a List of Files.
package test;
import java.io.File;
import java.io.IOException;
import java.util.List;
import org.apache.commons.io.FileUtils;
public class TestFiles {
public static void main(String[] args) throws IOException {
File dir = new File("<dir>");
String[] extensions = new String[] { "txt" };
List<File> files = (List<File>) FileUtils.listFiles(dir, extensions, true);
}
}
I am trying to get Japanese input from a JTextField (with the getText() method) and saving that to a File. I am confident that it does get Japanese format from the JTextField since I can append() that String to a JTextArea and it will be in the correct Japanese Format.
However, when I try to write to a File it only turns to gibberish! I have tried to use an OutputStreamWriter instantiated with StandardCharsets.UTF_8 and I have tried with a plain FileOutputStream where I send in the bytes from calling getBytes(StandardCharsets.UTF_8) on the String. In both cases the resulting file looks more like the following:
日本語ã�¯é›£ã�—ã�„ã�¨æ€�ã�†ï¼�å¦ã�³ã�Ÿã�„ã�ªã‚‰ã€�日本ã�§ä½�ã‚€
Which is not what I want, naturally. Does anyone have any idea what the issue might be?
I'm pretty sure you are creating the file with ISO-8859-1 instead UTF-8.
I'm also inferring you are using Eclipse because your previous questions.
Change your workspace settings
Window -> Preferences -> General -> Workspace : UTF-8
Default encoding for all content types
TestClass
This is the class i used to test the theory
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class test {
public static void main(String[] args) throws IOException {
File fileDir = new File("test.txt");
String japanese = "路権ち点節ヤトツ限聞ド勇売質タカア";
Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileDir)));
out.append(japanese);
System.out.println(japanese);
out.flush();
out.close();
}
}
Input/output with different settings
OutputFileISO: 路権ã¡ç¹ç¯ã¤ããéèãå売質ã¿ã«ã¢
OutputFileUTF8: 路権ち点節ヤトツ限聞ド勇売質タカア
I'm currently trying to read lines from a text only file that I have. I found on another stackoverflow(Reading a plain text file in Java) that you can use Files.lines(..).forEach(..)
However I can't actually figure out how to use the for each function to read line by line text, Anyone know where to look for that or how to do so?
Sample content of test.txt
Hello
Stack
Over
Flow
com
Code to read from this text file using lines() and forEach() methods.
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.stream.Stream;
public class FileLambda {
public static void main(String args[]) {
Path path = Paths.of("/root/test.txt");
try (Stream<String> lines = Files.lines(path)) {
lines.forEach(s -> System.out.println(s));
} catch (IOException ex) {
// do something or re-throw...
}
}
}
Avoid returning a list with:
List<String> lines = Files.readAllLines(path); //WARN
Be aware that the entire file is read when Files::readAllLines is called, with the resulting String array storing all of the contents of the file in memory at once.
Therefore, if the file is significantly large, you may encounter an OutOfMemoryError trying to load all of it into memory.
Use stream instead: Use Files.lines(Path) method that returns a Stream<String> object and does not suffer from this same issue.
The contents of the file are read and processed lazily, which means that only a small portion of the file is stored in memory at any given time.
Files.lines(path).forEach(System.out::println);
With Java 8, if file exists in a classpath:
Files.lines(Paths.get(ClassLoader.getSystemResource("input.txt")
.toURI())).forEach(System.out::println);
Files.lines(Path) expects a Path argument and returns a Stream<String>. Stream#forEach(Consumer) expects a Consumer argument. So invoke the method, passing it a Consumer. That object will have to be implemented to do what you want for each line.
This is Java 8, so you can use lambda expressions or method references to provide a Consumer argument.
I have created a sample , you can use the Stream to filter/
public class ReadFileLines {
public static void main(String[] args) throws IOException {
Stream<String> lines = Files.lines(Paths.get("C:/SelfStudy/Input.txt"));
// System.out.println(lines.filter(str -> str.contains("SELECT")).count());
//Stream gets closed once you have run the count method.
System.out.println(lines.parallel().filter(str -> str.contains("Delete")).count());
}
}
Sample input.txt.
SELECT Every thing
Delete Every thing
Delete Every thing
Delete Every thing
Delete Every thing
Delete Every thing
Delete Every thing
How do I:
Write in .txt file: Automatically create 100 blank records (fields: record id,name,age,etc) in a .txt file at the start of the program. Record id wont be blank
edit: I will enter a record id (ranging from 1-100) to add or edit data to the blank record, record id cant be edited
display in JOptionPane: I will enter a record id and all corresponding data will be displayed in JOptionPane (I know how to use JOptionPane to display stuff, but i dont know how to display only the selected data from a .txt file)
Can anyone please help to me how to do a program like this?
I know java, but im still a noob.
ok so far this is what I've got. no idea what to do next
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
public class writer {
public void writing() {
try {
File Text = new File(filepath here);
FileOutputStream FOS = new FileOutputStream(Text);
OutputStreamWriter OSW = new OutputStreamWriter(FOS);
Writer w = new BufferedWriter(OSW);
for(int x=1;x<101;x++){
w.write("Account #"+x);
}w.close();
} catch (IOException e) {
System.err.println("Problem writing to the file!");
}
}
public static void main(String[]args) {
writer write = new writer();
write.writing();
}
}
Ok, this sounds a lot like homework, so I'll give you some pointers which should hopefully allow you to find the results yourself with some directed searching...
Depending on how much data you wish to put in the .txt file, you might want to edit it by hand, in a CSV format:
accountId,name,age,etc
You are looking to have 100 records - while you can do it this way, you could start with just a handful created by hand, as an initial step, before writing something to produce your records.
After that, you need to design your model (ie. the Account object), this is likely to be a Plain Old Java Object (POJO), which is a standard class, with some private attributes, and getters and setters to access the data stored within.
You'll also need to read in the source data file and turn them into (Account) objects that will be later used - in instances like this, I like to use the BufferedReader class, as it allows you to read in an entire line of a text file in one go:
BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(new (File("/path/to/file")))));
You are then able to read in a line of the file with String line = reader.readLine()
Look at the methods available in the String class to see if you can find a suitable method to break up a string, based on a given separating value (in this case a comma, since it's csv) - you then create a new Account object and populate it with the values provided.
Several people have (rightly) pointed out the use of a Map to store the created objects - Hint: Look up HashMap (the account id can be the key)
When it comes to getting input from the user, JOptionPane.showInputDialog() will be what you need (parentComponent can be null)
I hope that is enough to get you going, without actually completing your homework for you.
If you have more questions, feel free to ask away.