How do I store an entire file into an array? - arrays

so I want to store the file I read into an array but I am not sure how to. I am trying to use an arraylist but when I compile it in the console I don't it is not the same as the text file
this is my code
public static void main(String[] args) {
BufferedReader br = null;
FileReader fr = null;
String line = null;
ArrayList<String> list = new ArrayList<String>();
try {
fr = new FileReader("sample.txt");
br = new BufferedReader(fr);
while ((line = br.readLine()) != null) {
list.add(line);
line = br.readLine();
for(String s : list){
System.out.println(s);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}

it looks to me like you're double advancing your position in the file by having line=br.readLine() both in your while condition and after adding to the ArrayList. Also, is there a reason that you're outputting the contents before you've processed the entire file instead of outside the while loop?

Related

File.ReadLines keeps file locked after reading it and i can't write into it

For some reason File.ReadLines keeps the file that im reading locked, and when i am trying to write text into it using a streamWriter, i get an error that it is being used by another process. If i don't read it first, writing into it works fine. Here is my code:
IEnumerable<String> lines;
private void loadCfg()
{
lines = File.ReadLines(Application.StartupPath + #"\server.cfg");
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}
Well you should read all the lines using StreamReader class that way your file will be properly closed I altered the way you are reading lines to read all lines using StreamReader try the following version
List<string> lines = new List<string>()
private void loadCfg()
{
string temp = null;
StreamReader rd = new StreamReader(Application.StartupPath + #"\server.cfg");
temp = rd.ReadLine();
while(temp != null)
{
lines.Add(temp);
temp = rd.ReadLine();
}
rd.Close();
foreach (var line in lines)
{
if (line.Contains("Port"))
{
portTxtBox.Text = extractValue(line);
}
if (line.Contains("Cars"))
{
maxCarsCombo.Text = extractValue(line);
}
if (line.Contains("MaxPlayers"))
{
maxPlayerCombo.Text = extractValue(line);
}
}
}
private void saveBtn_Click(object sender, EventArgs e)
{
StreamWriter sw = new StreamWriter(Application.StartupPath + #"\server.cfg",false);
sw.WriteLine(lines.ElementAt(0));
sw.Close();
}
I have not tested the code but I am sure it will solve your problem

How to add data from a text file to ComboBox in JavaFX?

I create a ComboBox in Scene Builder and I want to populate him with data from a text file (eg. Text.txt):
public class ToDoListController implements Initializable {
#FXML
private ComboBox<?> eventsSelector;
How to do this?
Thank you very much!
Two solutions:
1.
#FXML
private ComboBox eventsSelector;
#Override
public void initialize(URL location, ResourceBundle resources) {
List<String> myList;
try {
myList = Files.lines(Paths.get("path of my text file")).collect(Collectors.toList());
eventsSelector.setItems(FXCollections.observableArrayList(myList));
} catch (IOException e) {
System.out.println("Don t find file");
}
}
2.
//Read items from txt File
try {
BufferedReader br = new BufferedReader(new
FileReader("path of my text file"));
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
//Add Item
eventsSelector.getItems().add(line);
sb.append(line);
line = br.readLine();
}
br.close();
} catch (IOException e) {
System.out.println("Don t find file");
}
Since you want to add content from a .txt file the items in the ComboBox are Strings so you can change to this :
#FXML
private ComboBox<String> eventsSelector;
Then you need a list of the elements that you want to add to the ComboBox<String>, then you can add them simply by:
List<String> myList = Files.lines(path).collect(Collectors.toList());
comboBox.setItems(FXCollections.observableArrayList(myList));
I wrote some code for you, this should work for you:
public class YourController {
//Combobox
#FXML
ComboBox<String> combobx;
//Initialize FXML
#FXML
public void initialize() throws IOException {
//Read items from txt File
BufferedReader br = new BufferedReader(new FileReader("/items.txt"));
try {
StringBuilder sb = new StringBuilder();
String line = br.readLine();
while (line != null) {
//Add Item
combobx.getItems().add(line);
sb.append(line);
line = br.readLine();
}
} finally {
br.close();
}
//Default Selection first item
combobx.getSelectionModel().select(0);
}
}
The txt file must be in this case in the root directory of your project.

Opening a file for editing

I want to create a method that will load a txt file and then change it but thats another method.
private void openFile() {
fileChooser.getSelectedFile();
JFileChooser openFile = new JFileChooser();
openFile.showOpenDialog(frame);
}
What must go next in order to get data from the file after choosing it to manipulate its data?
The JFileChooser documentation has an example on how to continue your code, and get the name of the file chosen, which can then be turned into a File object. You should be able to modify that example to meet your needs:
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"JPG & GIF Images", "jpg", "gif");
chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " +
chooser.getSelectedFile().getName());
}
Here's an example that might help you. I would want to read up on and try some simple examples on different buffers that will read and write. In fact, i have worked with these a lot in the last few months and I still have to go and look.
public class ReadWriteTextFile {
static public String getContents(File aFile) {
StringBuilder contents = new StringBuilder();
try {
BufferedReader input = new BufferedReader(new FileReader(aFile));
try {
String line = null; //not declared within while loop
while (( line = input.readLine()) != null){
contents.append(line);
contents.append(System.getProperty("line.separator"));
}
}
finally {
input.close();
}
}
catch (IOException ex){
ex.printStackTrace();
}
return contents.toString();
}
static public void setContents(File aFile,
String aContents)
throws FileNotFoundException,
IOException {
if (aFile == null) {
throw new IllegalArgumentException("File should not be null.");
}
if (!aFile.exists()) {
throw new FileNotFoundException ("File does not exist: " + aFile);
}
if (!aFile.isFile()) {
throw new IllegalArgumentException("Should not be a directory: " + aFile);
}
if (!aFile.canWrite()) {
throw new IllegalArgumentException("File cannot be written: " + aFile);
}
Writer output = new BufferedWriter(new FileWriter(aFile));
try {
output.write( aContents );
}
finally {
output.close();
}
}
public static void main (String... aArguments) throws IOException {
File testFile = new File("C:\\Temp\\test.txt");//this file might have to exist (I am not
//certain but you can trap the error with a
//TRY-CATCH Block.
System.out.println("Original file contents: " + getContents(testFile));
setContents(testFile, "The content of this file has been overwritten...");
System.out.println("New file contents: " + getContents(testFile));
}
}

StringBuilder encoding in Java

I have a method which loads file from sdcard (Android) and then reads it with StringBuilder. The text which im reading is written with my native language characters such as ą ś ć ź ż...
StringBuilder (or FileInputStream) can't read them properly unfortunately. How I can set proper encoding ?
here is the code :
File file = new File(filePath);
FileInputStream fis = null;
StringBuilder builder = new StringBuilder();
try {
fis = new FileInputStream(file);
int content;
while ((content = fis.read()) != -1) {
builder.append((char) content);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (fis != null)
fis.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
System.out.println("File Contents = " + builder.toString());
contactService.updateContacts(builder.toString());
for example you could try an InputStreamReader combinded with a BufferedReader, that should do the trick:
InputStreamReader inputStreamReader = new InputStreamReader((InputStream)fis, "UTF-8");
BufferedReader br = new BufferedReader(inputStreamReader);
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
sb.append(line);
}
So long,
Tom

SHA-1 not giving the same answer

I'm trying to implement SHA-1 on Android with the following code
String name = "potato";
MessageDigest md = MessageDigest.getInstance("SHA-1");
md.update(name.getBytes("iso-8859-1"), 0 , name.getBytes( "iso-8859-1").length );
Bytes[] sha1hash = md.digest();
textview.setText(sha1hash.toString());
but when i run this code twice, it gives me different hash codes to "potato". As far as i know they should give me the same answer every time i run the program, anyone have any idea what problem could it be?
You can use this Code for getting SHA-1 value.
public class sha1Calculate {
public static void main(String[] args)throws Exception
{
File file = new File("D:\\Android Links.txt");
String outputTxt= "";
String hashcode = null;
try {
FileInputStream input = new FileInputStream(file);
ByteArrayOutputStream output = new ByteArrayOutputStream ();
byte [] buffer = new byte [65536];
int l;
while ((l = input.read (buffer)) > 0)
output.write (buffer, 0, l);
input.close ();
output.close ();
byte [] data = output.toByteArray ();
MessageDigest digest = MessageDigest.getInstance( "SHA-1" );
byte[] bytes = data;
digest.update(bytes, 0, bytes.length);
bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for( byte b : bytes )
{
sb.append( String.format("%02X", b) );
}
System.out.println("Digest(in hex format):: " + sb.toString());
}catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Try this Link for any Help.
http://www.mkyong.com/java/how-to-generate-a-file-checksum-value-in-java/

Resources