【UE4/UE5 C++】UE 打开Windows文件夹窗口,读写TXT/JSON文本

1.新建UE C++项目,新建蓝图函数库的C++类。

 2.在头文件.h中添加以下代码,将函数暴露给蓝图

public:
	UFUNCTION(BlueprintCallable, Category = "OpenAndcReadFile")  
		static FString OpenWindowsFile();  //打开Windows文件夹窗口
    UFUNCTION(BlueprintCallable, Category = "OpenAndcReadFile")
		static FString ReadFile(FString TxtPath);  //读入txt/json文件
    UFUNCTION(BlueprintCallable, Category = "OpenAndcReadFile")
		static bool WriteFile(FStirng Content,FString TxtPath);  //写入txt/json文件

3.在cpp文件中添加实现代码

   添加以下头文件引用

#include "Runtime\Core\Public\Misc\FileHelper.h"
#include "Runtime\Core\Public\Misc\Paths.h"
#include "Developer\DesktopPlatform\Public\IDesktopPlatform.h"
#include "Developer\DesktopPlatform\Public\DesktopPlatformModule.h"

  函数实现

FString UMyBlueprintFunctionLibrary::OpenWindowsFile() 
{
	/*定义默认打开路径*/
	FString DefaultPath = FPaths::ConvertRelativePathToFull(FPaths::ProjectDir());

	/*定义筛选文件类型*/
	FString FileType = TEXT("*.json");
	IDesktopPlatform* DesktopPlatform = FDesktopPlatformModule::Get();

	/*用于保存选中文件后返回的路径*/
	TArray<FString> PathNames;

	/*调用引擎的OpenFileDialog函数;其中EFileDialogFlags::None 为单选文件,EFileDialogFlags::Multiple 允许多选文件*/
	DesktopPlatform->OpenFileDialog(nullptr, TEXT("请选择文件"), DefaultPath, TEXT(""), *FileType, EFileDialogFlags::None, PathNames);

	/*判断是否返回有效路径*/
	if (PathNames.Num() > 0)
	{
		/*是,返回路径*/
		return PathNames[0];
	}
	else
		/*否,返回空字符串*/
		return TEXT("");
}
FString UMyBlueprintFunctionLibrary::ReadTxt(FString TxtPath)
{
	
	FString TxtStream;//文本流
	//查找文本是否存在
	if (!FPlatformFileManager::Get().GetPlatformFile().FileExists(*TxtPath))
	{
		FString str = TxtPath + "文件不存在!";
		UE_LOG(LogTemp, Warning, TEXT("%s,文件不存在!"), *str);
		return TxtStream;
	}
	//读取文本
	FFileHelper::LoadFileToString(TxtStream, *TxtPath);
	//写入文本
	//FFileHelper::SaveStringToFile(TxtStream, *TxtPath);

	return TxtStream;

}
bool UMyBlueprintFunctionLibrary::WriteFile(FString Content, FString TxtPath)
{
	bool result;
	result = FFileHelper::SaveStringToFile(Content, *TxtPath);
	return result;
}

4.在UE编辑器中进行编译,然后在蓝图中使用函数

5.读入的json文件可使用Varest插件进行解析后,对数据进行应用  

猜你喜欢

转载自blog.csdn.net/qq_27033865/article/details/138603127