How can I turn a txt file into a string just using its path? - android-studio

So I have a program that turns a .txt file into a string to then send it via bluetooth to a printer, the problem is that right now I'm doing it using the file name but I wanted to do it only using the path of the file, this has to do with the fact that I need to search on the folder for any existing txt files and if there are any I need to print the first one and then delete it, so I can't be doing it by using the file's name. This is my code so far:
private fun readFile() String {
val file = File(storage/emulated/0/IS4-PDF-RDP/00233116695912019091310005913BLUETOOTH.txt)
var ins InputStream = file.inputStream()
read contents of IntputStream to String
var content = ins.readBytes().toString(Charset.defaultCharset())
return content
}

You can find the first file in the folder read it and then delete it as per your requirements
File("/storage/emulated/0/IS4-PDF-RDP/").walk().find {
it.extension == "txt"
}?.apply {
inputStream().readBytes().toString(Charset.defaultCharset())
delete()
}

Related

How to use contains() to check if a String is inside the ArrayList?

I need to search a String in a text file that the content in the text file will always be appended(in other method). For example String "abcdefg" need to be search exactly same in the file.
ArrayList<String> List = new ArrayList<String>();
FileReader filereader = new FileReader(file);
BufferedReader bufferreader = new BufferedReader(filereader);
String linetxt;
while((linetxt = bufferreader.readLine())!=null)
{
List.add(linetxt);
List.add("\r\n");
}
System.out.println("Please enter a string: ");
String usern = input.next();
System.out.println(List);
if ((List.contains(usern.substring(0,usern.length()))));
{
System.out.println("String existed.");
}
bufferreader.close();
The Test File current content (will always be added new content):
abcde12345
This is my code, but it occurs a problem that I will always get "String existed" no matter what I input(the String I input is not in the text file but it still printing that the String existed).
How can I modify my code to make that if my input is contained in the ArrayList, it will return "String existed"?
Is it any other ways to search a String in a text file(the content of text file will be appended in other method)?
Thanks.............. Hope everyone safe.

GroovyScript Read from file and save in Property

I'm trying to read content from a file and then save it in a property in SoapUi.
What the file looks like (test.txt):
1231434324
1231414144
2413131231
4142131231
2131231231
My code:
File files = new File("/Temp/test.txt") // File
def lines = files.readLines(); //
lines.each {
System.out.println it
testRunner.testCase.testSteps["Properties"].setPropertyValue( "test", it )
};
For some reason it is only saving the last value (1231434324) in the property.
The below example actually saves all the values to the property but it also inserts square brackets in the beginning and at the end of the property value.
[123123123123, 123124234353, 231231231241, 213123123123]
File files = new File("/Temp/test.txt")
def lines = files.readLines();
testRunner.testCase.testSteps["Properties"].setPropertyValue( "test", "$lines" )
You can read the entire file contents into a String first, then set it all at once:
String value = new File('/Temp/test.txt').text
testRunner.testCase.testSteps['Properties'].setPropertyValue('test', value)
UPDATE
To get the total lines of the file, you could do this:
int count = value.split('\n').size()

How to write into XML file in Haxe?

I am using Haxe and OpenFL and I got a program that generates a Xml file.
However, I can't figure out how to save that file. I can create Xml tree and check it's valid, but for my life I can't figure out how to write the file.
So, in simple, how to do I write(and create) a file in Haxe? I want to be able to save my newly created Xml File (they serve as sort of settings file and initialization files for my program) on computer, so that I can load it later?
Found the solution right after writing this question.
Solution is to first to use sys.io.File.write() to create the file, then File.saveContent() to save the data in. You can get string from Xml with toString function, the ultimate solution looks like this:
if (!FileSystem.exists("maps"))
{
FileSystem.createDirectory("maps");
}
var number:Int = 1;
if (FileSystem.exists("maps/" + filename + ".xml"))
{
while(FileSystem.exists("maps/" + filename + number +".xml"))
{
number++;
}
filename = filename + number;
}
File.write("maps/" + filename + ".xml", false);
File.saveContent("maps/" + filename + ".xml", root.toString());
This checks if the directory exist and if not, create it and if the file exist, create a new numbered file rather than override it (for the moment, still working on the save feature)
This solution only works on c++, haven't tested others much yet but Flash does not work

Search fileName and get full path based on a pattern in C#

How do I get the full path for a file based on first 6 letters in the filename in C#? Is there any Regex for this?
I have a folder with 500K+ images.
All the images are named as per the database column value.
I am querying the table and based on the column value I have to search the folder for the specific file.
If the column value is 209050 there will be one file in the folder like 209050.pdf or 209050_12345.pdf. There will always be one image for 209050.
Please help
var files = Directory.EnumerateFiles(#"C:\MyRootDir", "209050*", SearchOption.AllDirectories);
This will return an enumerable of strings. Each string will the full path of the file whose name matches the specified pattern, in this case, any file whose name begins with '209050', irrespective of the extension. This will even search within sub directories of the folder MyRootDir.
If you wish to only filter for jpg files, change the 2nd argument accordingly.
var files = Directory.EnumerateFiles(#"C:\MyRootDir", "209050*.jpg", SearchOption.AllDirectories);
In case you are NOT using .Net Framework 4 or 4.5, you could use the GetFiles method instead.
var files = Directory.GetFiles(#"C:\MyRootDir", "209050*.jpg", SearchOption.AllDirectories);
The following will show you all .jpg files starting with 209050 in C:\MyDirectory:
using System;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string[] myFiles = Directory.GetFiles(#"C:\MyDirectory");
foreach (var x in myFiles)
{
string[] splitName = x.Split('\\');
string fileName = splitName[splitName.Length - 1];
if (fileName.StartsWith("209050") && fileName.EndsWith(".jpg"))
{
Console.WriteLine(x);
}
}
Console.ReadLine();
}
}
}
Here is my directory:
Here is the output:
Does this help?

Replace part of a filename in C#

I have a folder with .pdf files. In the names of most files I want to replace specific string with another string.
Here's what I've written.
private void btnGetFiles_Click(object sender, EventArgs e)
{
string dir = tbGetFIles.Text;
List<string> FileNames = new List<string>();
DirectoryInfo DirInfo = new DirectoryInfo(dir);
foreach (FileInfo File in DirInfo.GetFiles())
{
FileNames.Add(File.Name);
}
lbFileNames.DataSource = FileNames;
}
Here I extract all file names in List Box.
private void btnReplace_Click(object sender, EventArgs e)
{
string strReplace = tbReplace.Text; // The existing string
string strWith = tbWith.Text; // The new string
string dir = tbGetFIles.Text;
DirectoryInfo DirInfo = new DirectoryInfo(dir);
FileInfo[] names = DirInfo.GetFiles();
foreach (FileInfo f in names)
{
if(f.Name.Contains(strReplace))
{
f.Name.Replace(strReplace, strWith);
}
}
And here I want to do the replacing, but something is going wrong. What?
It sounds like you want to change the name of the file on disk. If so then you need to use the File.Move API vs. changing the actual string which is the file name.
One other mistake you are making is the Replace call itself. A string in .Net is immutable and hence all of the mutating APIs like Replace return a new string vs. changing the old one in place. To see the change you need to assign the new value back to a variable
string newName = f.Name.Replace(strReplace, strWith);
File.Move(f.Name, newName);
f.Name is a read-only property. f.Name.Replace(..) simply returns a new string with the filename you want, but never actually changes the file.
I suggest something along the following, though I haven't tested it:
File.Move(f.Name, f.Name.Replace(strReplace, strWith));
Replace return another string, it doesn't change the original string.
So you need to write
string newName = f.Name.Replace(strReplace, strWith);
of course this doesn't change the name of the file on disk.
If that was your intention then you should look at
File.Move(f.Name, newName);
also keep in mind that File.Move will fail with an exception if the destination file exists.
See here for an example
At a first glance, seems like you're not reassigning the replaced string to your f.Name variable. Try this:
string NewFileName = f.Name.Replace(strReplace, strWith);
File.Copy(f.Name, NewFileName);
File.Delete(f.Name);
When you call string.Replace this doesn't alter your existing string. Instead it is returning a new string.
You need to change your code to something like this:
if(f.Name.Contains(strReplace))
{
string newFileName = f.Name.Replace(strReplace, strWith);
//and work here with your new string
}

Resources