How to display a filenames (.txt) in JTextArea? - java

This method shows only a name of file in console.
JTextArea area = new JTextArea(20,40);
public void readContent(){
KreatorPytan kp = new KreatorPytan();
File file = new File("D:\\IT\\JAVA\\zadanie\\Testy");
File[] files = file.listFiles();
for(int i = 0; i < files.length; i++){
try {
BufferedReader reader = null;
reader = new BufferedReader(new FileReader(files[i]));
if(files[i].isFile()){
System.out.println(files[i].getName());
area.read(reader, "File");
}
} catch (FileNotFoundException ex) {
Logger.getLogger(WyborPytan.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(WyborPytan.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
I don't know why these names of files are not saving to my jtextarea. Can you help me?

This code is reading files to JTextArea and rewriting each previous file contents with the next. So as result you will see the last file contents. If you want to get file names in JTextArea, you don't need to read file, just do smth like
for (int i = 0; i < files.length; i++) {
area.append(files[i].getName() + '\n');
}

Related

Create text file dynamically in a specified directory, write data,read data from that file in java

Recently i have tried to write code of above given title and the problem is that i could not get sufficient date to write upon have a look at my code .it is showing some errors like
it is showing invalid token for semicolon after tagfile.createnewfile();
let us look at code:
public class WriteToFileExample {
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
boolean bool=false;
File f = new File(path);
File f1 = new File(fname);
try {
f1.createNewFile();
bool=f.mkdirs() ;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static final String FILENAME = "G:\\Software\\Files\\anil.txt";
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String content = null;
String[] str = new String[100];
try (BufferedWriter bw = new BufferedWriter(new FileWriter(FILENAME))) {
System.out.println(" enter no.of line to be inserted into file");
int k = sc.nextInt();
for (int i = 0; i <= k; i++) {
System.out.println(" enter " + i + " line data");
content = sc.nextLine();
bw.write(content);
str[i] = content;
}
System.out.println("The content present in\n
G:\Software\Files\anil.txt is:");
for (int i = 1; i <= k; i++)
System.out.println(str[i]);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Please find the code and then you can use
**Writing** : PrintWriter,Scanner,BufferedWriter etc to write to that file
**Reading** :FileReader,BufferReader,Scanner with these readers etc
String path = "G:"+File.separator+"Software"+File.separator+"Files";
String fname= path+File.separator+"fileName.txt";
File f = new File(path);
File f1 = new File(fname);
f.mkdirs() ;
try {
f1.createNewFile();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Ref : https://www.lynda.com/Java-tutorials/Reading-writing-text-files/107061/113497-4.html
Refer above video which may help

Java : Writing a String to a JPG File

Alright, so I am writing a small program that should have taken 10 minutes to complete however I am running into unforeseen problems.
The program should take in some old files I had in a vault program on my old phone, they are basically Jpg files but with an added "obscured" text to the front of the file.
So below is my code logic
get a folder input for the files,
create an arraylist containing each actual file.
call ConvertFiles to convert the file to a string,
delete the first 8 characters using substring and save that temp file to another arraylist containing the strings.
decode that string as base64 and input that into a bytearrayinputstream and save that to a bufferedimage.
This is where the problem occurs. I have content all the way up to the ImageIO.read(bis), so when it tries to write to a new file it throws the image == null
from the ImageTypeSpecifier. I have tried multiple ways of decoding and encoding the string, but any help is wanted and if any more information is needed I will provide it!
public class ImageConvert {
private File folder;
private ArrayList<File> files;
private ArrayList<String> stringFiles = new ArrayList<>();
private ArrayList<BufferedImage> bfImages = new ArrayList<>();
boolean isRunning = true;
Scanner scanner = new Scanner(System.in);
String folderPath;
public static void main(String[] args) {
ImageConvert mc = new ImageConvert();
mc.mainCode();
}
public void mainCode(){
System.out.println("Please enter the folder path: ");
folderPath = scanner.nextLine();
folder = new File(folderPath);
//System.out.println("folderpath: " + folder);
files = new ArrayList<File>(Arrays.asList(folder.listFiles()));
convertFiles();
}
public void convertFiles(){
for(int i = 0; i < files.size(); i++){
try {
String temp = FileUtils.readFileToString(files.get(i));
//System.out.println("String " + i + " : " + temp);
stringFiles.add(temp.substring(8));
} catch (IOException ex) {
Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
null, ex);
}
}
//System.out.println("Converted string 1: " + stringFiles.get(0));
for(int j = 0; j < stringFiles.size(); j++){
BufferedImage image = null;
byte[] imageByte;
try {
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(stringFiles.get(j));
System.out.println(imageByte.toString());
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
bfImages.add(image);
} catch (IOException ex) {
Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
null, ex);
}
}
System.out.println("Image 1: " + bfImages.get(0));
for(int k = 0; k < bfImages.size(); k++){
try {
ImageIO.write(bfImages.get(k), "jpg",
new File(folderPath + "/" + k + ".jpg"));
} catch (IOException ex) {
Logger.getLogger(ImageConvert.class.getName()).log(Level.SEVERE,
null, ex);
}
}
}
}
This is an example of my files:
The following example uses the file you included with your question. You don't need to do any decoding, just read the file into memory, store the 8 byte String and then write the remaining bytes to a jpg from an 8 byte offset.
Just adapt the method below to work with your: "folder input for files". You don't need an ArrayList containing each actual jpg file.
public void convertFiles() {
File imgFile;
byte[] bytes;
FileOutputStream fos;
String temp;
for (int i = 0; i < files.size(); i++) {
temp = "";
try {
// 'read' method can be found below
bytes = read(files.get(i));
// read the 8 byte string from the beginning of the file
for(int j = 0; j < 8; j++) {
temp += (char) bytes[j];
}
imgFile = new File("img.jpg");
// points to './img.jpg'
fos = new FileOutputStream(imgFile);
// write from offset 8 to end of 'bytes'
fos.write(bytes, 8, bytes.length - 8);
fos.close();
} catch (FileNotFoundException e) {
// Logger stuff
} catch (IOException ex) {
// Logger stuff
}
System.out.println("[temp]:> " + temp);
}
}
read(File file) method adapted from a community wiki answer to File to byte[] in Java
public byte[] read(File file) throws IOException {
ByteArrayOutputStream ous = null;
InputStream ios = null;
try {
byte[] buffer = new byte[4096];
ous = new ByteArrayOutputStream();
ios = new FileInputStream(file);
int read = 0;
while ((read = ios.read(buffer)) != -1) {
ous.write(buffer, 0, read);
}
} finally {
try {
if (ous != null)
ous.close();
} catch (IOException e) {
}
try {
if (ios != null)
ios.close();
} catch (IOException e) {
}
}
return ous.toByteArray();
}
Output:
[temp]:> obscured
Image File:

Need to read from a txt file in the assets folder in android studio

My buddy and I are writing a simple app in Android Studio. When you push a button, a new activity opens with the name of the button you pushed and displays the text in that file.
I have the code that generates the first set of buttons (these are hard coded), and I can get the name of the buttons pushed. My trouble is reading the text file and displaying the contents. Each line in the text file is a word that needs to be the text value of a button. I can't hard code the words because they can change often.
Example; On the main activity you push the button labeled "Round", it sends you to a page that has all the words in the text file named "round" listed as buttons.
I asked this question earlier, but it was put on hold as too vague.
I hope this is more clear.
Here's the code I'm using, but need the code to read the file. This is not working right.
I can't get it to display even the first line. The file contents are this ---
Pipe
Elbow
Reducer
Tap on flat
EC
Please help.
Thanks in advance.
public class test extends Activity {
int counter = 0;
protected void onCreate(Bundle savedInstanceState) {
counter = 0;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);
BufferedReader reader = null;
try {
reader = new BufferedReader(
new InputStreamReader(getAssets().open("round.txt")));
// do reading, usually loop until end of file reading
String mLine;
while ((mLine = reader.readLine()) != null) {
for (int row = 0; row < 10; row++) {
TableRow tblRow = new TableRow(this);
tblRow.setPadding(5, 30, 5, 5);
table.addView(tblRow);
int NUM_COL = 3;
for (int col = 0; col != NUM_COL; col++) {
Button btn = new Button(this);
btn.setText(mLine);
tblRow.addView(btn);
NUM_COL++;
}
}
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
}
}
Here's an image of my structure:
Well I found the answer. Thank you for pointing me in the right direction.
Here it is
try {
InputStream is = getAssets().open("round.txt");
// We guarantee that the available method returns the total
// size of the asset... of course, this does mean that a single
// asset can't be more than 2 gigs.
int size = is.available();
// Read the entire asset into a local byte buffer.
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
// Convert the buffer into a string.
String text = new String(buffer);
// Finally stick the string into the text view.
// Replace with whatever you need to have the text into.
TextView tv = (TextView)findViewById(R.id.text);
tv.setText(text);
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
Reworked the code and this is the one that works.
BufferedReader reader;
try {
InputStream is = getAssets().open("round.txt");
reader = new BufferedReader(new InputStreamReader(is));
// Finally stick the string into the text of the button.
TableLayout table = (TableLayout) findViewById(R.id.tblLayoutContent);
String line = reader.readLine();
int lineLength = (line.length());
while (line != null){
TableRow tblRow = new TableRow(this);
tblRow.setPadding(5, 30, 5, 5);
table.addView(tblRow);
for (int col = 0; col < NUM_COL; col++) {
Button btn = new Button(this);
btn.setTextSize(14);
btn.setText(line);
tblRow.addView(btn);
line = reader.readLine();
}
};
} catch (IOException e) {
// Should never happen!
throw new RuntimeException(e);
}
}
U can read from a file, line by line like this:
String filename = "filename.txt";
BufferedReader bufferedReader = null;
try {
bufferedReader = new BufferedReader(new InputStreamReader
(this.getAssets().open(filename), StandardCharsets.UTF_8));
String line;
while ((line = bufferedReader.readLine()) != null) {
//add the lines in some arraylist if you want to set them.
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
In Kotlin , we can do as
val string = requireContext().assets.open("round.txt").bufferedReader().use {
it.readText()
}
Try this... add getResources()
reader = new BufferedReader(
new InputStreamReader(getResources().getAssets().open("round.txt")));

Java Reading Text File Yielding Null Result

Here I have some code where I create an ActionListener for a JCheckBox.
Once the user clicks the JCheckBox the actionlistener is triggered and this code runs.
First I check whether they are selecting it or deselecting the check box and I input this into the text file. I re-input the checkbox's text plus a 0 if the user is deselecting it or a 1 if they are selecting it.
However, when I try to read through my file using a loop it seems to only result in null values. Here is an excerpt of exactly what I'm talking about.
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
The notes.length is an array that contains the amount of lines of my file. I've also tried changing that to an int that held line the line count. No change, still didn't work. If I print out "text" and "s" I get the checkbox's text value followed by "null". The text variable should have a value.
I get a NullPointerException..
selected
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at SideNotes$2.actionPerformed(SideNotes.java:86)
By the way.. when I read the file in other places I do not get a NullPointerException. It returns the line just fine.
Full code:
File file = new File("notes.txt");
if (file.exists()) {
try {
FileInputStream fs = new FileInputStream(file);
final BufferedReader br = new BufferedReader(
new InputStreamReader(fs));
final BufferedReader reader = new BufferedReader(
new FileReader("notes.txt"));
FileWriter writer = new FileWriter(file, true);
final BufferedWriter brw = new BufferedWriter(writer);
while (reader.readLine() != null)
lines++;
// reader.close();
notes = new JCheckBox[lines];
ActionListener al = new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
JCheckBox checkbox = (JCheckBox) e.getSource();
if (checkbox.isSelected()) {
System.out.println("selected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
} else {
System.out.println("deselected");
String s = checkbox.getText();
for (int i = 0; i < notes.length; i++) {
String text;
try {
text = br.readLine();
if (text.contains(s)) {
brw.write(s + "0");
brw.newLine();
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
}
};
Why am I getting a null result, and how do I fix it?
I think this one should be :
String s = checkBox.getText().toString();
so you can set the value of text as String.

Read the files in a folder and then store each user id in a linkedhashset

I have around 100 files in a folder. And I am trying to read all those files one by one. Each file will have data like this and each line resembles an user id.
960904056
6624084
1096552020
750160020
1776024
211592064
1044872088
166720020
1098616092
551384052
113184096
136704072
So I need to read that file line by line and then store each user id in a LinkedHashSet. I am able to read all the files from a particular folder with the below code. But with the below java code that I wrote, I am not sure how to read those files line by line and then store each user id in a LinkedHashSet?
public static void main(String args[]) {
File folder = new File("C:\\userids-20130501");
File[] listOfFiles = folder.listFiles();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
try {
String content = FileUtils.readFileToString(file);
System.out.println(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
Any help will be appreciated on this? And any better way to do the same process?
Since you are using FileUtils. The class has the method readLines() which returns a list of String.
You can then add this List of String to LinkedHashSet by using the addAll() method.
Try this -
public static void main(String args[]) {
File folder = new File("C:\\userids-20130501");
File[] listOfFiles = folder.listFiles();
Set<String> userIdSet = new LinkedHashSet<String>();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
try {
List<String> content = FileUtils.readLines(file, Charset.forName("UTF-8"));
userIdSet.addAll(content);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use the readLine() method of BufferedReader to read a file line by line as below:
public static void main(String args[]) {
File folder = new File("C:\\userids-20130501");
File[] listOfFiles = folder.listFiles();
Set<String> userIdSet = new LinkedHashSet<String>();
for (int i = 0; i < listOfFiles.length; i++) {
File file = listOfFiles[i];
if (file.isFile() && file.getName().endsWith(".txt")) {
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while((line = br.readLine()) != null) {
userIdSet.add(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
If I understood you correctly then you can do something like below.
// Change generic if you want Integer
Set<String> userIdSet = new LinkedHashSet<String>();
// Your code
String content = FileUtils.readFileToString(file);
// Creating array by splitting for every new line content
String[] stn = content.split("\\n");
for(String xx : stn){
// parse it as Integer if you changed the generic
// Adding the file content to Set
userIdSet.add(xx);
}
Here are a the things I would do different.
Using an iterator for the files
The new try statement allows opening up a “resource” in a try block and automatically closing the resource when the block is done. Ref
Excluding invalid files with a continue statement. This removes one level of nesting. See this post.
All of these changes are highly opinionated of course.
public static void main(String[] args) {
Set<Integer> users = new LinkedHashSet<Integer>();
File dir = new File("C:\\userids-20130501");
for (File child : dir.listFiles()) {
if (!child.isFile() || !child.getName().endsWith(".txt")) {
continue;
}
try (BufferedReader in = new BufferedReader(
new FileReader(child.getPath()))) {
String id = null;
while ((id = in.readLine()) != null) {
users.add(Integer.parseInt(id));
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}

Categories

Resources