I'm trying to read a text files and insert the data from these text files into a URL;
but i have this error "java.lang.illegalargumentexception contains a path separator file"
this is the read method that im using
>
public String ReadFile (String Path){
String res = null;
try {
String filePath = android.os.Environment.getExternalStorageDirectory().getPath() + "/" + Path;
File file = new File(filePath);
if(file.exists()){
InputStream in = openFileInput(filePath);
if (in != null) {
// prepare the file for reading
InputStreamReader input = new InputStreamReader(in);
BufferedReader buffreader = new BufferedReader(input);
res = "";
String line;
while (( line = buffreader.readLine()) != null) {
res += line;
}
in.close();
}else{
}
}else{
Toast.makeText(getApplicationContext(), "The File" + Path + " not Found" ,Toast.LENGTH_SHORT).show();
}
} catch(Exception e){
Toast.makeText(getApplicationContext(),e.toString() + e.getMessage(),Toast.LENGTH_SHORT).show();
}
return res;
}
> String sendername = ReadFile ("SenderName.txt");
String AccountName = ReadFile ("AccountName.txt");
String AccountPassword = ReadFile ("AccountPassword.txt");
String MsgText = ReadFile ("MsgText.txt");
Thanks,
- Though this error doesn't points there, but still have you given the permission to read External Storage in the Manifest.xml file
Try something like this..
public void readFile(String path){
File f = new File(path);
FileReader fr = new FileReader(f);
BufferedReader br = new BufferedReader(fr);
String read = new String();
String temRead = new String();
while((temRead = br.readLine())!=null){
read = read + temRead;
}
}
Related
I want to save multiple txt files in one txt file and delete the previous ones.
What method can I use?
Code I wrote myself:
public static void mergeFile() throws IOException {
long unixTime = System.currentTimeMillis() / 1000L;
final String sysName = String.valueOf(unixTime);
File directory = new File("src/");
FileWriter myWriter = new FileWriter("src/"+sysName+".txt",true);
File[] files = directory.listFiles();
for(File file : files) {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
String aLine;
String fileName = file.toString();
int split = fileName.indexOf(".");
long fName = Long.parseLong(fileName.substring(5, split)) ;
if (fName < unixTime) {
while ((aLine = in.readLine()) != null) {
myWriter.write(aLine);
myWriter.write("\n");
}
in.close();
file.delete();
}
}
}
I rewrote the above code as follows and it worked properly.
public static void mergeFile() throws IOException {
long unixTime = System.currentTimeMillis() / 1000L;
final String sysName = String.valueOf(unixTime);
File directory = new File("src/raw/");
File[] files = directory.listFiles();
FileWriter myWriter = new FileWriter("src/ok/"+sysName+".txt");
for(File file : files) {
String aLine;
String fileName = file.toString();
int split = fileName.indexOf(".");
long fName = Long.parseLong(fileName.substring(15, split)) ;
if (fName <= unixTime) {
FileInputStream fis = new FileInputStream(file);
BufferedReader in = new BufferedReader(new InputStreamReader(fis));
while ((aLine = in.readLine()) != null) {
myWriter.write(aLine);
myWriter.write("\n");
}
in.close();
}
Files.move(Paths.get("src/raw/"+fName+".txt"),
Paths.get("src/old/"+fName+".txt"));
}
myWriter.close();
Query.insertSyslog("src/ok/"+sysName+".txt");
}
This is what I have... I know it should require a loop or perhaps the .empty() method from the File class, but I'm not sure.. any help is appreciated.
What I have will open a file, read from the file on each line, and then return back the amount of characters in the file, the amount of words in the file, and the number of sentences in the file.
public class FileExample{
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
boolean fileFound = false;
try{
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
if(!file.exists()){
}
while((line = reader.readLine()) != null){
if(!(line.equals(""))){
...
}
}
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
System.out.println("output data");
}
}
You need to make a while loop and move the try block inside the loop.
while(true){
try{
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
if(!file.exists()){
continue;
}
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
while((line = reader.readLine()) != null){
if(!(line.equals(""))){
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
String[] sentenseList = line.split("[!?.:]+");
sentenseCount += sentenseList.length;
}
}
break;
}
catch(FileNotFoundException e){
System.out.println("File not found.");
}
}
Use a while loop, until the file exists. Example:
...
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
while(!fileFound){
System.out.println("The file does not exist. What is the name of the file?");
inputFile = in.nextLine();
file = new File(inputFile);
fileFound = file.exists();
}
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
...
Add a do-while to your code. Like this. not exactly sure if that's gonna run but i hope you get the idea
do {
try {
System.out.println("What is the name of the file?");
inputFile = in.nextLine();
File file = new File(inputFile);
fileFound = file.exists();
FileInputStream fileStream = new FileInputStream(file);
InputStreamReader input = new InputStreamReader(fileStream);
BufferedReader reader = new BufferedReader(input);
while((line = reader.readLine()) != null){
if(!(line.equals(""))){
characterCount += line.length();
String[] wordList = line.split("\\s+");
countWord += wordList.length;
String[] sentenseList = line.split("[!?.:]+");
sentenseCount += sentenseList.length;
}
}
} catch (FileNotFoundException e){
System.out.println("File not found.");
}
} while (!fileFound) {
System.out.println("Character count: "+characterCount);
System.out.println("Word count: "+countWord);
System.out.println("Sentence count: "+sentenseCount);
}
I'm doing a phonebook and I'd like to save contacts to vcard. I found vcard format on the internet, but I do not know how to read datas from stdin.
package homework;
import java.io.*;
public class SaveToVcard {
public static void vcard() throws IOException {
File file = new File("contact.vcf");
FileOutputStream fop = new FileOutputStream(file);
if (file.exists()) {
String vcard = "BEGIN:VCARD\n" + "VERSION:4.0\n" + "N:Gump;Forrest;;;\n" + "FN:Forrest Gump\n"
+ "ORG:Bubba Gump Shrimp Co.\n" + "TITLE:Shrimp Man\n"
+ "TEL;TYPE=work,voice;VALUE=uri:tel:+1-111-555-1212\n"
+ "TEL;TYPE=home,voice;VALUE=uri:tel:+1-404-555-1212\n" + "EMAIL:forrestgump#example.com\n"
+ "REV:20080424T195243Z\n" + "END:VCARD";
fop.write(vcard.getBytes());
BufferedReader br = null;
String currentLine;
br = new BufferedReader(new FileReader("contact.vcf"));
while ((currentLine = br.readLine()) != null) {
System.out.println(currentLine);
}
fop.flush();
fop.close();
System.out.println("Kész");
} else
System.out.println("A fájl nem létezik");
}
You can use Scanner and do something like this
Scanner sc = new Scanner(System.in);
String input = sc.next();
See https://docs.oracle.com/javase/8/docs/api/java/util/Scanner.html
Or maybe you can pass what you need as parameters when running your application
See https://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html
I am able to read in a file right now, but I am confused on how to read then the strings line by line to run through a parser I created. Any suggestions would be helpful.
public void ReadBtn() {
char[] inputBuffer = new char[READ_BLOCK_SIZE];
int charRead;
String s = "";
int READ_BLOCK_SIZE = 100;
//reading text from file
try {
FileInputStream fileIn = openFileInput("mytextfile.txt");
InputStreamReader InputRead = new InputStreamReader(fileIn);
BufferedReader BR = new BufferedReader(InputRead);
while((charRead = InputRead.read(inputBuffer)) > 0) {
// char to string conversion
String readstring = String.copyValueOf(inputBuffer, 0, charRead);
s += readstring;
getContactInfo(s);
}
InputRead.close();
} catch(Exception e) {
e.printStackTrace();
}
}
-Try this code. Replace sdCard path to your file path where mytextfile.txt exists.
String sdCard = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "mytextfile.txt";
String path = sdCard + "/" + MarketPath + "/";
File directory = new File(path);
if (directory.exists()) {
File file = new File(path + fileName);
if (file.exists()) {
String myData = ""; // this variable will store your file text
try {
FileInputStream fis = new FileInputStream(file);
DataInputStream in = new DataInputStream(fis);
BufferedReader br =new BufferedReader(new InputStreamReader(in));
String strLine;
while ((strLine = br.readLine()) != null) {
myData = myData + strLine;
}
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
You can read all lines in an ArrayList:
public void ReadBtn() {
int READ_BLOCK_SIZE = 100;
ArrayList<String> linesList = new ArrayList<>();
// reading text from file
try {
FileInputStream fileIn=openFileInput("mytextfile.txt");
InputStreamReader InputRead= new InputStreamReader(fileIn);
BufferedReader br = new BufferedReader(InputRead);
String line = br.readLine();
while (line != null) {
linesList.add(line);
line = br.readLine();
}
InputRead.close();
// here linesList contains an array of strings
for (String s: linesList) {
// do something for each line
}
} catch (Exception e) {
e.printStackTrace();
}
}
I am trying to replace multiple strings in a file from source as ArrayList. But the application is erasing the old string before replacing a new one. Please help.
public static void writeNewFile(File template, ArrayList<String> data) {
File file = template;
String nameToReplace = "((name))";
String productToReplace = "((product))";
String giftToReplace = "((gift))";
String giftValueToReplace = "((gift-value))";
String outputFileName = data.get(0);
String workingDirectory = System.getProperty("user.dir");
Scanner scanner = null;
try {
scanner = new Scanner(file);
PrintWriter writer = new PrintWriter(workingDirectory + "\\Output\\" + outputFileName);
while (scanner.hasNextLine()) {
String line1 = scanner.nextLine();
writer.println(line1.replace(nameToReplace, data.get(1)));
writer.println(line1.replace(productToReplace, data.get(2)));
}
} catch (Exception e) {
System.out.println("Destination folder not found");
}
}
This worked for me
try {
BufferedReader reader = new BufferedReader(new FileReader(file));
String line = "", oldtext = "";
while ((line = reader.readLine()) != null) {
oldtext += line + "\r\n";
}
reader.close();
String result = oldtext.replace(nameToReplace, data.get(1))
.replace(productToReplace, data.get(2))
.replace(giftToReplace, data.get(3));
// Write updated record to a file
FileWriter writer = new FileWriter(workingDirectory + "\\Output\\" + outputFileName);
writer.write(result);
writer.close();
} catch (IOException ioe) {
System.out.println("Write error");
}