I want to populate a JList from a .txt
I can't populate the JList...
Here's the code:
The .txt is formatted like this sample:
name1
name2
name3
The JList is declared in this way:
private javax.swing.JList jList1
This is the method used to read line by line:
private void visualizzaRosa(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
fileSquadra = squadra.getText();
try {
FileInputStream fstream = new FileInputStream("C:/Users/Franky/Documents....");
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
Jlist1.add(strline); //to populate jlist
System.out.println(strLine); //to print on consolle
}
in.close();
} catch (Exception e) {
}
}
Thanks
Try
DefaultListModel listModel = new DefaultListModel();
while ((strLine = br.readLine()) != null)
{
listModel.addElement(strline);
System.out.println(strLine);
}
jList1.setModel(listModel);
and if i want to populate a Jtextarea instead of the jlist ????
Then use the read() method that is part of the API. THere is no need to write custom code:
textArea.read(...);
Related
This question already has answers here:
Java reading a file into an ArrayList?
(13 answers)
Closed 6 years ago.
I would like to read in a file (game-words.txt) via a buffered reader into an ArrayList of Strings. I already set up the buffered reader to read in from game-words.txt, now I just need to figure out how to store that in an ArrayList. Thanks ahead for any help and patience!
Here is what I have so far:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOExecption;
class Dictionary{
String [] words; // or you can use an ArrayList
int numwords;
// constructor: read words from a file
public Dictionary(String filename){ }
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
System.out.println(line);
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
Reading strings into array:
Automatic:
List<String> strings = Files.readAllLines(Path);
Manual:
List<String> strings = new ArrayList<>();
while ((line = br.readLine()) != null){
strings.add(line);
}
Splitting lines to words (if one line contains several words):
for(String s : strings) {
String[] words = s.split(" "); //if words in line are separated by space
}
This could be helpful too:
class Dictionary{
ArrayList<String> words = new ArrayList<String>(); // or you can use an ArrayList
int numwords;String filename;
// constructor: read words from a file
public Dictionary(String filename){
this.filename =filename;
}
BufferedReader br = null;
String line;
try {
br = new BufferedReader(new FileReader("game-words.txt"));
while ((line = br.readLine()) != null){
words.add(line.trim());
}
} catch (IOExecption e) {
e.printStackTrace();
}
}
I have used trim which will remove the leading and the trailing spaces from the words if there are any.Also, if you want to pass the filename as a parameter use the filename variable inside Filereader as a parameter.
Yes, you can use an arrayList to store the words you are looking to add.
You can simply use the following to deserialize the file.
ArrayList<String> pList = new ArrayList<String>();
public void deserializeFile(){
try{
BufferedReader br = new BufferedReader(new FileReader("file_name.txt"));
String line = null;
while ((line = br.readLine()) != null) {
// assuming your file has words separated by space
String ar[] = line.split(" ");
Collections.addAll(pList, ar);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
This question already has an answer here:
populate a 'JTable' with values from a '.txt' file
(1 answer)
Closed 7 years ago.
I have a text file like this
0786160384|P. K.|Tharindu|912921549v|Colombo|
0711495765|P. K.|Gamini|657414589v|Colombo|
0114756199|H. P.|Weerasigha|657895478v|Kandy|
each |separates a data. I want to display the data on this file in a jTable. below is my code so far.
public class PrintGUI extends javax.swing.JFrame {
File file, tempFile;
FileReader fileReader;
FileWriter fileWriter;
ArrayList ClientList;
Vector data = new Vector();
Vector columns = new Vector();
public PrintGUI() {
initComponents();
this.setIconImage(new ImageIcon(getClass().getResource("/Images/icon.png")).getImage());
file = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\phonebook.txt");
tempFile = new File("C:\\Users\\Tharindu\\Documents\\NetBeansProjects\\Geo phonebook\\tempphonebook.txt");
}
#SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
PhoneBookTable.setModel(new javax.swing.table.DefaultTableModel(
new Object [][] {
},
new String [] {
"Phone No", "First Name", "Last Name", "NIC", "City"
}
)
}
private void formWindowOpened(java.awt.event.WindowEvent evt) {
String line = null;
DefaultTableModel dtm = (DefaultTableModel) PhoneBookTable.getModel();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
StringTokenizer st1 = new StringTokenizer(br.readLine(), "|");
while (st1.hasMoreTokens()) {
columns.addElement(st1.nextToken());
}
while ((line = br.readLine()) != null) {
StringTokenizer st2 = new StringTokenizer(line, "|");
while (st2.hasMoreTokens()) {
data.addElement(st2.nextToken());
}
}
br.close();
dtm.addRow(new Object[]{columns, data});
} catch (Exception e) {
e.printStackTrace();
}
}
problem is when I run the program it shows a whole line on text from the .txt file instead of a single data per column.
more specifically it shows the whole line of
[0786160384, P. K., Tharindu, 912921549v, Colombo]
in the first row first column and
[0711495765, P. K., Gamini, 657414589v, Colombo, 0114756199, H. P., Weerasigha, 657895478v, Kandy]
in the first row second column
Instead I want it to display single data per cell. can some one please help?
You only call addRow once, so of course there will be only one row added to the table model.
You need to move that statement inside your file-reading loop.
Each line you read from the file corresponds to a row in your table. As such, you need to call addRow each time you have read a line, and call it with the contents of that line.
Finally found the error. It should be like
try {
BufferedReader br = new BufferedReader(new FileReader(file));
while ((line = br.readLine()) != null) {
data = new Vector();// this is important
StringTokenizer st1 = new StringTokenizer(line, "|");
while (st1.hasMoreTokens()) {
String nextToken = st1.nextToken();
data.add(nextToken);
System.out.println(nextToken);
}
System.out.println(data);
dtm.addRow(data);//add here
System.out.println(".................................");
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
I've been trying to read a file for the last few days and have tried following other answers but have not succeeded. This is the code I currently have to import the text file:
public ArrayList<String> crteDict() {
try {
BufferedReader br = new BufferedReader
(new FileReader("/program/res/raw/levels.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] linewrds = line.split(" ");
words.add(linewrds[0].toLowerCase());
// process the line.
}
br.close();
}
catch (FileNotFoundException fe){
fe.printStackTrace();
It is meant to read the text file and just create a long Array of words. It keeps ending up in the FileNotFoundException.
Please let me know any answers.
Thanks!
IF your file is stored in the res/raw folder of the android project, you can read it as follows, this code must be inside an Activity class, as this.getResources() refers to Context.getResources():
// The InputStream opens the resourceId and sends it to the buffer
InputStream is = this.getResources().openRawResource(R.raw.levels);
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String readLine = null;
try {
// While the BufferedReader readLine is not null
while ((readLine = br.readLine()) != null) {
Log.d("TEXT", readLine);
}
// Close the InputStream and BufferedReader
is.close();
br.close();
} catch (IOException e) {
e.printStackTrace();
}
public static void main(String[] args) {
ArrayList<String> studentTokens = new ArrayList<String>();
ArrayList<String> studentIds = new ArrayList<String>();
try {
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream(new File("file1.txt"));
BufferedReader br = new BufferedReader(new InputStreamReader(fstream, "UTF8"));
String strLine;
// Read File Line By Line
while ((strLine = br.readLine()) != null) {
strLine = strLine.trim();
if ((strLine.length()!=0) && (!strLine.contains("#"))) {
String[] students = strLine.split("\\s+");
studentTokens.add(students[TOKEN_COLUMN]);
studentIds.add(students[STUDENT_ID_COLUMN]);
}
}
for (int i=0; i<studentIds.size();i++) {
File file = new File("query.txt"); // The path of the textfile that will be converted to csv for upload
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String newtext = oldtext.replace("sanid", studentIds.get(i)).replace("salabel",studentTokens.get(i)); // Here the name "sanket" will be replaced by the current time stamp
FileWriter writer = new FileWriter("final.txt",true);
writer.write(newtext);
writer.close();
}
fstream.close();
br.close();
System.out.println("Done!!");
} catch (Exception e) {
e.printStackTrace();
System.err.println("Error: " + e.getMessage());
}
}
The above code of mine reads data from a text file and query is a file that has a query in which 2 places "sanid" and "salabel" are replaced by the content of string array and writes another file final . But when i run the code the the final does not have the queries. but while debugging it shows that all the values are replaced properly.
but while debugging it shows that all the values are replaced properly
If the values are found to be replaced when you debugged the code, but they are missing in the file, I would suggest that you flush the output stream. You are closing the FileWriter without calling flush(). The close() method delegates its call to the underlying StreamEncoder which does not flush the stream either.
public void close() throws IOException {
se.close();
}
Try this
writer.flush();
writer.close();
That should do it.
How would I read a .txt file in Java and put every line in an array when every lines contains integers, strings, and doubles? And every line has different amounts of words/numbers.
I'm a complete noob in Java so sorry if this question is a bit stupid.
Thanks
Try the Scanner class which no one knows about but can do almost anything with text.
To get a reader for a file, use
File file = new File ("...path...");
String encoding = "...."; // Encoding of your file
Reader reader = new BufferedReader (new InputStreamReader (
new FileInputStream (file), encoding));
... use reader ...
reader.close ();
You should really specify the encoding or else you will get strange results when you encounter umlauts, Unicode and the like.
Easiest option is to simply use the Apache Commons IO JAR and import the org.apache.commons.io.FileUtils class. There are many possibilities when using this class, but the most obvious would be as follows;
List<String> lines = FileUtils.readLines(new File("untitled.txt"));
It's that easy.
"Don't reinvent the wheel."
The best approach to read a file in Java is to open in, read line by line and process it and close the strea
// Open the file
FileInputStream fstream = new FileInputStream("textfile.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fstream));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null) {
// Print the content on the console - do what you want to do
System.out.println (strLine);
}
//Close the input stream
fstream.close();
To learn more about how to read file in Java, check out the article.
Your question is not very clear, so I'll only answer for the "read" part :
List<String> lines = new ArrayList<String>();
BufferedReader br = new BufferedReader(new FileReader("fileName"));
String line = br.readLine();
while (line != null)
{
lines.add(line);
line = br.readLine();
}
Common used:
String line = null;
File file = new File( "readme.txt" );
FileReader fr = null;
try
{
fr = new FileReader( file );
}
catch (FileNotFoundException e)
{
System.out.println( "File doesn't exists" );
e.printStackTrace();
}
BufferedReader br = new BufferedReader( fr );
try
{
while( (line = br.readLine()) != null )
{
System.out.println( line );
}
#user248921 first of all, you can store anything in string array , so you can make string array and store a line in array and use value in code whenever you want. you can use the below code to store heterogeneous(containing string, int, boolean,etc) lines in array.
public class user {
public static void main(String x[]) throws IOException{
BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
String[] user=new String[500];
String line="";
while ((line = b.readLine()) != null) {
user[i]=line;
System.out.println(user[1]);
i++;
}
}
}
This is a nice way to work with Streams and Collectors.
List<String> myList;
try(BufferedReader reader = new BufferedReader(new FileReader("yourpath"))){
myList = reader.lines() // This will return a Stream<String>
.collect(Collectors.toList());
}catch(Exception e){
e.printStackTrace();
}
When working with Streams you have also multiple methods to filter, manipulate or reduce your input.
For Java 11 you could use the next short approach:
Path path = Path.of("file.txt");
try (var reader = Files.newBufferedReader(path)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
Or:
var path = Path.of("file.txt");
List<String> lines = Files.readAllLines(path);
lines.forEach(System.out::println);
Or:
Files.lines(Path.of("file.txt")).forEach(System.out::println);