How to create file in java - string

File Name = new File("G:/Java/lesson25_1/Name.txt");
if(Name==null){
JOptionPane.showMessageDialog(this, "Details are missing");
}
try{
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
when i do this in a method it dosn't work when i click the button

There is a method for file called exists to check if the given file exist or not.
String path = "G:/Java/lesson25_1/Name.txt";
File file = new File(path);
if(!file.isFile() || !file.canRead()){
JOptionPane.showMessageDialog(this, "Details are missing");
} else {
try {
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
} catch (Exception e){
e.printStackTrace();
}
}

Related

SharePoint - Timeout Error - Copying Folder To Another Folder

When I call this method enough times, I think I'm getting throttled because I'm seeing a connection timeout (instead of a 429).
I have a large set of files in a folder that I'm looking to copy to another folder, and looking for suggestions.
Thanks!
public void AddNewFileAndCheckIn(string sharepointFolderRelativeURL, string localFilePath, string indexName)
{
try
{
// Get the Folder
//Folder fileFolder = Web.GetFolderByServerRelativeUrl(this.GetFolderRelativeUrl(sharepointFolderPath));
var initTimeout = ClientContext.RequestTimeout;
var timespans = new List<TimeSpan>();
timespans.Add(TimeSpan.FromSeconds(300));
timespans.Add(TimeSpan.FromSeconds(300));
Polly.Retry.RetryPolicy policy = Polly.Policy.Handle<Exception>().WaitAndRetry(timespans);
policy.Execute(() => {
using (var reader = new System.IO.StreamReader(localFilePath))
{
Folder fileFolder = Web.GetFolderByServerRelativeUrl(sharepointFolderRelativeURL);
// Add the File
FileCreationInformation fci = new FileCreationInformation();
fci.ContentStream = reader.BaseStream; // System.IO.File.ReadAllBytes(localFilePath);
fci.Url = System.IO.Path.GetFileName(localFilePath);
fileFolder.Files.Add(fci);
ClientContext.Load(fileFolder);
ClientContext.RequestTimeout = initTimeout * 10;
ClientContext.ExecuteQuery();
// Get the newly checked in (added) SP File
File fileToCheck = Web.GetFileByServerRelativeUrl(System.IO.Path.Combine(fileFolder.ServerRelativeUrl, fci.Url));
ClientContext.Load(fileToCheck, item => item, item => item.ListItemAllFields["Created"], item => item.ListItemAllFields["Modified"]);
ClientContext.ExecuteQuery();
// Update Metadata
fileToCheck.ListItemAllFields["Created"] = new System.IO.FileInfo(localFilePath).CreationTime;
fileToCheck.ListItemAllFields["Modified"] = new System.IO.FileInfo(localFilePath).LastWriteTime;
fileToCheck.ListItemAllFields["Index"] = indexName;
fileToCheck.ListItemAllFields.Update();
ClientContext.ExecuteQuery();
}
});
}
catch (WebException wex)
{
throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), wex);
}
catch (Exception ex)
{
// Catch and Rethrow with Details
//throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderPath, localFilePath, indexName), ex);
throw new SharepointOnlineException(string.Format("Exception In AddNewFileAndCheckIn('{0}','{1}', '{2}')", sharepointFolderRelativeURL, localFilePath, indexName), ex);
}
}

System.out.println displays blank line

Why does the below 'System.out.println'(fileEncodedString) display a blank line while the value is there when I debug and I do get an output when I decode the value and print.
byte[] fileContent = readFileToByteArray(filePath);
String fileEncodedString = Base64.getEncoder().encodeToString(fileContent);
byte[] fileDecodedString = Base64.getDecoder().decode(fileEncodedString);
System.out.println("Base64 Decoded File (Basic): " + new String(fileDecodedString, "utf-8"));
private static byte[] readFileToByteArray(String filePath) {
FileInputStream fileInputStream = null;
byte[] bytesArray = null;
try {
File file = new File(filePath);
bytesArray = new byte[(int) file.length()];
// read file into bytes[]
fileInputStream = new FileInputStream(file);
fileInputStream.read(bytesArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return bytesArray;
}
Try to use below method for readFileToByteArray and pass correct file path:
static byte[] readFileToByteArray(String filePath) throws IOException {
File file = new File(filePath);
return Files.readAllBytes(file.toPath());
}
its working fine.

FileInputStream issue - App has stopped working

I am having trouble with FileInputStream in Android Studio. My application has stopped working when I use it to read file .txt in the internal memory (I have writen data to this file successfully). I have try many solutions but they didn't work. Can anyone give the solution for this problem? Here is my code. Thanks very much. (I have added users-permission "WRITE_EXTERNAL_STORAGE" and "READ_EXTERNAL_STORAGE").
String fileName = "infoProfile.txt";
private int readData() {
try {
String path = MainActivity.this.getFilesDir().getAbsolutePath() + "/" + fileName;
FileInputStream in = openFileInput(path);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
ArrayList<String> str = new ArrayList<>();
String data = "";
while ((data = reader.readLine()) != null) {
str.add(data);
}
in.close();
if (str.isEmpty())
return 0;
etName.setText(str.get(0));
etEmail.setText(str.get(1));
etPhone.setText(str.get(2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return 1;
}

Overwriting a file that is currently being used

I want to create a new sheet on an Excel workbook that is currently open/being used. In my program, I ask the user for a new worksheet name, but when I have the Excel file open, it returns me a FileNotFoundException because it "cannot access the file because it is being used by another process." Is it possible to fix this? Or should I ask the user to close the file first?
public void exportToExcel() {
String excelFileName = null; // the name/directory/address of the excel file created/selected
FileInputStream excelFileIn = null; // allows us to connect to the Excel file so we can read it
FileOutputStream excelFileOut = null; // allows us to connect to the Excel file so we can write to it
ExcelFileUtility eUtil = new ExcelFileUtility(); // used open an excel file
if(columnsQuery != null) {
try {
excelFileName = eUtil.getFile(FileExtensions.XLS);
if(excelFileName != null) {
excelFileIn = new FileInputStream(new File(excelFileName));
workbook = new HSSFWorkbook(excelFileIn);
exportColsToWorkbook(columnsQuery);
excelFileOut = new FileOutputStream(excelFileName);
workbook.write(excelFileOut);
// close everything
workbook.close();
excelFileIn.close();
excelFileOut.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}

FileOutputStream error

I had a part of code which suppose to get an image from website and store it into the sdcard. The following code was working find when i develop on sdk1.5. However, it was not working now after i change it to android sdk 2.0. This line got problem; FileOutputStream fos = new FileOutputStream(filepath + "/" + this.filename);
Here is the code that i have:
void downloadFile(String fileUrl) {
URL myFileUrl = null;
try {
myFileUrl = new URL(fileUrl);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection) myFileUrl
.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bmImg = BitmapFactory.decodeStream(is);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
String filepath = Environment.getExternalStorageDirectory()
.getAbsolutePath();
FileOutputStream fos = new FileOutputStream(filepath + "/"
+ this.filename);
bmImg.compress(CompressFormat.JPEG, 75, fos);
fos.flush();
fos.close();
Context context = this.getBaseContext();
new MediaScannerNotifier2(context, filepath + "/" + this.filename,
"image/jpeg");
// displaying download completion message
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Wallpaper Downloaded").setCancelable(false)
.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
btn_setwall.setEnabled(true);
btn_download.setEnabled(false);
}
});
AlertDialog alert = builder.create();
alert.show();
} catch (Exception e) {
Log.e("MyLog", e.toString());
}
}
The error occur in the 3rd catch. However, when i move this line
FileOutputStream fos = new
FileOutputStream(filepath + "/" +
this.filename);
to the 2nd try/catch, then it will occur in the 2nd catch.
Can please help me on this?
Maybe try getting rid of .getAbsolutePath()
This works for me on 2.2:
FileOutputStream fos = new FileOutputStream(Environment.getExternalStorageDirectory() + "/" + fileName);

Resources